diff --git a/.gitattributes b/.gitattributes
index 6ef435cfe5..3c4605c943 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -5,14 +5,9 @@ docs/operator-manual/resource_actions_builtin.md linguist-generated=true
docs/operator-manual/server-commands/argocd-*.md linguist-generated=true
docs/user-guide/commands/argocd_*.md linguist-generated=true
manifests/core-install.yaml linguist-generated=true
-manifests/core-install-with-hydrator.yaml linguist-generated=true
manifests/crds/*-crd.yaml linguist-generated=true
manifests/ha/install.yaml linguist-generated=true
-manifests/ha/install-with-hydrator.yaml linguist-generated=true
manifests/ha/namespace-install.yaml linguist-generated=true
-manifests/ha/namespace-install-with-hydrator.yaml linguist-generated=true
manifests/install.yaml linguist-generated=true
-manifests/install-with-hydrator.yaml linguist-generated=true
manifests/namespace-install.yaml linguist-generated=true
-manifests/namespace-install-with-hydrator.yaml linguist-generated=true
pkg/apis/api-rules/violation_exceptions.list linguist-generated=true
diff --git a/.github/workflows/bump-major-version.yaml b/.github/workflows/bump-major-version.yaml
deleted file mode 100644
index b7fbf7101a..0000000000
--- a/.github/workflows/bump-major-version.yaml
+++ /dev/null
@@ -1,89 +0,0 @@
-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: 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: 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: 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:
- 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
\ No newline at end of file
diff --git a/.github/workflows/ci-build.yaml b/.github/workflows/ci-build.yaml
index e1afc4a76b..718b3b2f8a 100644
--- a/.github/workflows/ci-build.yaml
+++ b/.github/workflows/ci-build.yaml
@@ -14,7 +14,7 @@ on:
env:
# Golang version to use across CI steps
# renovate: datasource=golang-version packageName=golang
- GOLANG_VERSION: '1.24.3'
+ GOLANG_VERSION: '1.24.4'
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
@@ -39,7 +39,7 @@ jobs:
files_yaml: |
backend:
- '!ui/**'
- - '!**.md'
+ - '!**.md'
- '!**/*.md'
- '!docs/**'
frontend:
@@ -94,8 +94,8 @@ jobs:
lint-go:
permissions:
- contents: read # for actions/checkout to fetch code
- pull-requests: read # for golangci/golangci-lint-action to fetch pull requests
+ contents: read # for actions/checkout to fetch code
+ pull-requests: read # for golangci/golangci-lint-action to fetch pull requests
name: Lint Go code
if: ${{ needs.changes.outputs.backend == 'true' }}
runs-on: ubuntu-22.04
@@ -109,7 +109,7 @@ jobs:
with:
go-version: ${{ env.GOLANG_VERSION }}
- name: Run golangci-lint
- uses: golangci/golangci-lint-action@971e284b6050e8a5849b72094c50ab08da042db8 # v6.1.1
+ uses: golangci/golangci-lint-action@4afd733a84b1f43292c63897423277bb7f4313a9 # v8.0.0
with:
# renovate: datasource=go packageName=github.com/golangci/golangci-lint versioning=regex:^v(?\d+)\.(?\d+)\.(?\d+)?$
version: v2.1.6
@@ -174,7 +174,7 @@ jobs:
- name: Run all unit tests
run: make test-local
- name: Generate test results artifacts
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
+ uses: actions/upload-artifact@b4b15b8c7c6ac21ea08fcf65892d2ee8f75cf882 # v4.4.3
with:
name: test-results
path: test-results
@@ -238,7 +238,7 @@ jobs:
- name: Run all unit tests
run: make test-race-local
- name: Generate test results artifacts
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
+ uses: actions/upload-artifact@b4b15b8c7c6ac21ea08fcf65892d2ee8f75cf882 # v4.4.3
with:
name: race-results
path: test-results/
@@ -333,15 +333,6 @@ jobs:
run: yarn lint
working-directory: ui/
- shellcheck:
- runs-on: ubuntu-latest
- steps:
- - uses: actions/checkout@8410ad0602e1e429cee44a835ae9f77f654a6694 # v4.0.0
- - run: |
- sudo apt-get install shellcheck
- shellcheck -e SC2086 -e SC2046 -e SC2068 -e SC2206 -e SC2048 -e SC2059 -e SC2154 -e SC2034 -e SC2016 -e SC2128 -e SC1091 -e SC2207 $(find . -type f -name '*.sh') | tee sc.log
- test ! -s sc.log
-
analyze:
name: Process & analyze test artifacts
if: ${{ needs.changes.outputs.backend == 'true' || needs.changes.outputs.frontend == 'true' }}
@@ -385,9 +376,9 @@ jobs:
run: |
go tool covdata percent -i=test-results,e2e-code-coverage/applicationset-controller,e2e-code-coverage/repo-server,e2e-code-coverage/app-controller,e2e-code-coverage/commit-server -o test-results/full-coverage.out
- name: Upload code coverage information to codecov.io
- uses: codecov/codecov-action@18283e04ce6e62d37312384ff67231eb8fd56d24 # v5.4.3
+ uses: codecov/codecov-action@b9fd7d16f6d7d1b5d2bec1a2887e65ceed900238 # v4.6.0
with:
- files: test-results/full-coverage.out
+ file: test-results/full-coverage.out
fail_ci_if_error: true
env:
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
@@ -411,31 +402,30 @@ jobs:
strategy:
fail-fast: false
matrix:
- # latest: true means that this version mush upload the coverage report to codecov.io
- # We designate the latest version because we only collect code coverage for that version.
k3s:
- - version: v1.32.1
- latest: true
- version: v1.31.0
- latest: false
+ # We designate the latest version because we only collect code coverage for that version.
+ latest: true
- version: v1.30.4
latest: false
- version: v1.29.8
latest: false
+ - version: v1.28.13
+ latest: false
needs:
- build-go
- changes
env:
GOPATH: /home/runner/go
- ARGOCD_FAKE_IN_CLUSTER: 'true'
- ARGOCD_SSH_DATA_PATH: '/tmp/argo-e2e/app/config/ssh'
- ARGOCD_TLS_DATA_PATH: '/tmp/argo-e2e/app/config/tls'
- ARGOCD_E2E_SSH_KNOWN_HOSTS: '../fixture/certs/ssh_known_hosts'
- ARGOCD_E2E_K3S: 'true'
- ARGOCD_IN_CI: 'true'
- ARGOCD_E2E_APISERVER_PORT: '8088'
- ARGOCD_APPLICATION_NAMESPACES: 'argocd-e2e-external,argocd-e2e-external-2'
- ARGOCD_SERVER: '127.0.0.1:8088'
+ ARGOCD_FAKE_IN_CLUSTER: "true"
+ ARGOCD_SSH_DATA_PATH: "/tmp/argo-e2e/app/config/ssh"
+ ARGOCD_TLS_DATA_PATH: "/tmp/argo-e2e/app/config/tls"
+ ARGOCD_E2E_SSH_KNOWN_HOSTS: "../fixture/certs/ssh_known_hosts"
+ ARGOCD_E2E_K3S: "true"
+ ARGOCD_IN_CI: "true"
+ ARGOCD_E2E_APISERVER_PORT: "8088"
+ ARGOCD_APPLICATION_NAMESPACES: "argocd-e2e-external,argocd-e2e-external-2"
+ ARGOCD_SERVER: "127.0.0.1:8088"
GITHUB_TOKEN: ${{ secrets.E2E_TEST_GITHUB_TOKEN || secrets.GITHUB_TOKEN }}
GITLAB_TOKEN: ${{ secrets.E2E_TEST_GITLAB_TOKEN }}
steps:
@@ -494,9 +484,9 @@ jobs:
git config --global user.email "john.doe@example.com"
- name: Pull Docker image required for tests
run: |
- docker pull ghcr.io/dexidp/dex:v2.43.0
+ docker pull ghcr.io/dexidp/dex:v2.41.1
docker pull argoproj/argo-cd-ci-builder:v1.0.0
- docker pull redis:7.2.7-alpine
+ docker pull redis:7.0.15-alpine
- name: Create target directory for binaries in the build-process
run: |
mkdir -p dist
@@ -526,13 +516,13 @@ jobs:
goreman run stop-all || echo "goreman trouble"
sleep 30
- name: Upload e2e coverage report
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
+ uses: actions/upload-artifact@b4b15b8c7c6ac21ea08fcf65892d2ee8f75cf882 # v4.4.3
with:
name: e2e-code-coverage
path: /tmp/coverage
if: ${{ matrix.k3s.latest }}
- name: Upload e2e-server logs
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
+ uses: actions/upload-artifact@b4b15b8c7c6ac21ea08fcf65892d2ee8f75cf882 # v4.4.3
with:
name: e2e-server-k8s${{ matrix.k3s.version }}.log
path: /tmp/e2e-server.log
diff --git a/.github/workflows/image-reuse.yaml b/.github/workflows/image-reuse.yaml
index 5c37240d04..426d2cbaa8 100644
--- a/.github/workflows/image-reuse.yaml
+++ b/.github/workflows/image-reuse.yaml
@@ -70,13 +70,12 @@ jobs:
uses: actions/setup-go@3041bf56c941b39c61721a86cd11f3bb1338122a # v5.2.0
with:
go-version: ${{ inputs.go-version }}
- cache: false
- name: Install cosign
uses: sigstore/cosign-installer@dc72c7d5c4d10cd6bcb8cf6e3fd625a9e5e537da # v3.7.0
- uses: docker/setup-qemu-action@49b3bc8e6bdd4a60e6116a5414239cba5943d3cf # v3.2.0
- - uses: docker/setup-buildx-action@6524bf65af31da8d45b59e8c27de4bd072b392f5 # v3.8.0
+ - uses: docker/setup-buildx-action@c47758b77c9736f4b2ef4073d4d51994fabfe349 # v3.7.1
- name: Setup tags for container image as a CSV type
run: |
diff --git a/.github/workflows/image.yaml b/.github/workflows/image.yaml
index e2ef286b4e..cbdaef5ef1 100644
--- a/.github/workflows/image.yaml
+++ b/.github/workflows/image.yaml
@@ -7,7 +7,7 @@ on:
pull_request:
branches:
- master
- types: [labeled, unlabeled, opened, synchronize, reopened]
+ types: [ labeled, unlabeled, opened, synchronize, reopened ]
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
@@ -46,14 +46,14 @@ jobs:
needs: [set-vars]
permissions:
contents: read
- packages: write # for pushing packages to GHCR, which is used by cd.apps.argoproj.io to avoid polluting Quay with tags
+ packages: write # for pushing packages to GHCR, which is used by cd.apps.argoproj.io to avoid polluting Quay with tags
id-token: write # for creating OIDC tokens for signing.
if: ${{ github.repository == 'argoproj/argo-cd' && github.event_name != 'push' }}
uses: ./.github/workflows/image-reuse.yaml
with:
# Note: cannot use env variables to set go-version (https://docs.github.com/en/actions/using-workflows/reusing-workflows#limitations)
# renovate: datasource=golang-version packageName=golang
- go-version: 1.24.3
+ go-version: 1.24.4
platforms: ${{ needs.set-vars.outputs.platforms }}
push: false
@@ -61,7 +61,7 @@ jobs:
needs: [set-vars]
permissions:
contents: read
- packages: write # for pushing packages to GHCR, which is used by cd.apps.argoproj.io to avoid polluting Quay with tags
+ packages: write # for pushing packages to GHCR, which is used by cd.apps.argoproj.io to avoid polluting Quay with tags
id-token: write # for creating OIDC tokens for signing.
if: ${{ github.repository == 'argoproj/argo-cd' && github.event_name == 'push' }}
uses: ./.github/workflows/image-reuse.yaml
@@ -70,7 +70,7 @@ jobs:
ghcr_image_name: ghcr.io/argoproj/argo-cd/argocd:${{ needs.set-vars.outputs.image-tag }}
# Note: cannot use env variables to set go-version (https://docs.github.com/en/actions/using-workflows/reusing-workflows#limitations)
# renovate: datasource=golang-version packageName=golang
- go-version: 1.24.3
+ go-version: 1.24.4
platforms: ${{ needs.set-vars.outputs.platforms }}
push: true
secrets:
@@ -101,8 +101,8 @@ jobs:
- build-and-publish
- set-vars
permissions:
- contents: write # for git to push upgrade commit if not already deployed
- packages: write # for pushing packages to GHCR, which is used by cd.apps.argoproj.io to avoid polluting Quay with tags
+ contents: write # for git to push upgrade commit if not already deployed
+ packages: write # for pushing packages to GHCR, which is used by cd.apps.argoproj.io to avoid polluting Quay with tags
if: ${{ github.repository == 'argoproj/argo-cd' && github.event_name == 'push' }}
runs-on: ubuntu-22.04
steps:
@@ -116,3 +116,4 @@ jobs:
git config --global user.name 'CI'
git diff --exit-code && echo 'Already deployed' || (git commit -am 'Upgrade argocd to ${{ needs.set-vars.outputs.image-tag }}' && git push)
working-directory: argoproj-deployments/argocd
+
diff --git a/.github/workflows/pr-title-check.yml b/.github/workflows/pr-title-check.yml
index 81c1981923..5c19a36a48 100644
--- a/.github/workflows/pr-title-check.yml
+++ b/.github/workflows/pr-title-check.yml
@@ -12,8 +12,8 @@ permissions: {}
# workflow being trigger a number of times. This limits it
# to one run per PR.
concurrency:
- group: ${{ github.workflow }}-${{ github.head_ref }}
- cancel-in-progress: true
+ group: ${{ github.workflow }}-${{ github.ref }}
+
jobs:
validate:
diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml
index b9b7d56439..04351e92d2 100644
--- a/.github/workflows/release.yaml
+++ b/.github/workflows/release.yaml
@@ -11,7 +11,7 @@ permissions: {}
env:
# renovate: datasource=golang-version packageName=golang
- GOLANG_VERSION: '1.24.3' # Note: go-version must also be set in job argocd-image.with.go-version
+ GOLANG_VERSION: '1.24.4' # Note: go-version must also be set in job argocd-image.with.go-version
jobs:
argocd-image:
@@ -25,7 +25,7 @@ jobs:
quay_image_name: quay.io/argoproj/argocd:${{ github.ref_name }}
# Note: cannot use env variables to set go-version (https://docs.github.com/en/actions/using-workflows/reusing-workflows#limitations)
# renovate: datasource=golang-version packageName=golang
- go-version: 1.24.3
+ go-version: 1.24.4
platforms: linux/amd64,linux/arm64,linux/s390x,linux/ppc64le
push: true
secrets:
@@ -33,20 +33,20 @@ jobs:
quay_password: ${{ secrets.RELEASE_QUAY_TOKEN }}
argocd-image-provenance:
- needs: [argocd-image]
- permissions:
- actions: read # for detecting the Github Actions environment.
- id-token: write # for creating OIDC tokens for signing.
- packages: write # for uploading attestations. (https://github.com/slsa-framework/slsa-github-generator/blob/main/internal/builders/container/README.md#known-issues)
- # Must be refernced by a tag. https://github.com/slsa-framework/slsa-github-generator/blob/main/internal/builders/container/README.md#referencing-the-slsa-generator
- if: github.repository == 'argoproj/argo-cd'
- uses: slsa-framework/slsa-github-generator/.github/workflows/generator_container_slsa3.yml@v2.0.0
- with:
- image: quay.io/argoproj/argocd
- digest: ${{ needs.argocd-image.outputs.image-digest }}
- secrets:
- registry-username: ${{ secrets.RELEASE_QUAY_USERNAME }}
- registry-password: ${{ secrets.RELEASE_QUAY_TOKEN }}
+ needs: [argocd-image]
+ permissions:
+ actions: read # for detecting the Github Actions environment.
+ id-token: write # for creating OIDC tokens for signing.
+ packages: write # for uploading attestations. (https://github.com/slsa-framework/slsa-github-generator/blob/main/internal/builders/container/README.md#known-issues)
+ # Must be refernced by a tag. https://github.com/slsa-framework/slsa-github-generator/blob/main/internal/builders/container/README.md#referencing-the-slsa-generator
+ if: github.repository == 'argoproj/argo-cd'
+ uses: slsa-framework/slsa-github-generator/.github/workflows/generator_container_slsa3.yml@v2.0.0
+ with:
+ image: quay.io/argoproj/argocd
+ digest: ${{ needs.argocd-image.outputs.image-digest }}
+ secrets:
+ registry-username: ${{ secrets.RELEASE_QUAY_USERNAME }}
+ registry-password: ${{ secrets.RELEASE_QUAY_TOKEN }}
goreleaser:
needs:
@@ -73,13 +73,11 @@ jobs:
uses: actions/setup-go@3041bf56c941b39c61721a86cd11f3bb1338122a # v5.2.0
with:
go-version: ${{ env.GOLANG_VERSION }}
- cache: false
- name: Set GORELEASER_PREVIOUS_TAG # Workaround, GoReleaser uses 'git-describe' to determine a previous tag. Our tags are created in release branches.
run: |
set -xue
- GORELEASER_PREVIOUS_TAG=$(go run hack/get-previous-release/get-previous-version-for-release-notes.go ${{ github.ref_name }}) || exit 1
- echo "GORELEASER_PREVIOUS_TAG=$GORELEASER_PREVIOUS_TAG" >> $GITHUB_ENV
+ echo "GORELEASER_PREVIOUS_TAG=$(go run hack/get-previous-release/get-previous-version-for-release-notes.go ${{ github.ref_name }})" >> $GITHUB_ENV
- name: Set environment variables for ldflags
id: set_ldflag
@@ -109,7 +107,7 @@ jobs:
- name: Generate subject for provenance
id: hash
env:
- ARTIFACTS: '${{ steps.run-goreleaser.outputs.artifacts }}'
+ ARTIFACTS: "${{ steps.run-goreleaser.outputs.artifacts }}"
run: |
set -euo pipefail
@@ -130,8 +128,8 @@ jobs:
# Must be refernced by a tag. https://github.com/slsa-framework/slsa-github-generator/blob/main/internal/builders/container/README.md#referencing-the-slsa-generator
uses: slsa-framework/slsa-github-generator/.github/workflows/generator_generic_slsa3.yml@v2.0.0
with:
- base64-subjects: '${{ needs.goreleaser.outputs.hashes }}'
- provenance-name: 'argocd-cli.intoto.jsonl'
+ base64-subjects: "${{ needs.goreleaser.outputs.hashes }}"
+ provenance-name: "argocd-cli.intoto.jsonl"
upload-assets: true
generate-sbom:
@@ -156,7 +154,6 @@ jobs:
uses: actions/setup-go@3041bf56c941b39c61721a86cd11f3bb1338122a # v5.2.0
with:
go-version: ${{ env.GOLANG_VERSION }}
- cache: false
- name: Generate SBOM (spdx)
id: spdx-builder
@@ -167,7 +164,7 @@ jobs:
SIGS_BOM_VERSION: v0.2.1
# comma delimited list of project relative folders to inspect for package
# managers (gomod, yarn, npm).
- PROJECT_FOLDERS: '.,./ui'
+ PROJECT_FOLDERS: ".,./ui"
# full qualified name of the docker image to be inspected
DOCKER_IMAGE: quay.io/argoproj/argocd:${{ github.ref_name }}
run: |
@@ -215,8 +212,8 @@ jobs:
# Must be referenced by a tag. https://github.com/slsa-framework/slsa-github-generator/blob/main/internal/builders/container/README.md#referencing-the-slsa-generator
uses: slsa-framework/slsa-github-generator/.github/workflows/generator_generic_slsa3.yml@v2.0.0
with:
- base64-subjects: '${{ needs.generate-sbom.outputs.hashes }}'
- provenance-name: 'argocd-sbom.intoto.jsonl'
+ base64-subjects: "${{ needs.generate-sbom.outputs.hashes }}"
+ provenance-name: "argocd-sbom.intoto.jsonl"
upload-assets: true
post-release:
@@ -299,7 +296,7 @@ jobs:
uses: peter-evans/create-pull-request@5e914681df9dc83aa4e4905692ca88beb2f9e91f # v7.0.5
with:
commit-message: Bump version in master
- title: 'chore: Bump version in master'
+ title: "chore: Bump version in master"
body: All images built from master should indicate which version we are on track for.
signoff: true
branch: update-version
diff --git a/.github/workflows/scorecard.yaml b/.github/workflows/scorecard.yaml
index 64650e5619..0403b1e2d8 100644
--- a/.github/workflows/scorecard.yaml
+++ b/.github/workflows/scorecard.yaml
@@ -54,7 +54,7 @@ jobs:
# Upload the results as artifacts (optional). Commenting out will disable uploads of run results in SARIF
# format to the repository Actions tab.
- name: "Upload artifact"
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
+ uses: actions/upload-artifact@b4b15b8c7c6ac21ea08fcf65892d2ee8f75cf882 # v4.4.3
with:
name: SARIF file
path: results.sarif
diff --git a/.gitpod.Dockerfile b/.gitpod.Dockerfile
index fa4f1691b0..ec47f2553d 100644
--- a/.gitpod.Dockerfile
+++ b/.gitpod.Dockerfile
@@ -1,4 +1,4 @@
-FROM gitpod/workspace-full@sha256:a47a68ee7f9da10cd889ccce4661bc73f2c0d5a98d3d087e8bdfc0230b27964c
+FROM gitpod/workspace-full@sha256:230285e0b949e6d728d384b2029a4111db7b9c87c182f22f32a0be9e36b225df
USER root
diff --git a/.golangci.yaml b/.golangci.yaml
index 38783894c5..4f01cf66d8 100644
--- a/.golangci.yaml
+++ b/.golangci.yaml
@@ -1,229 +1,101 @@
-formatters:
- enable:
- - gofumpt
- - goimports
-
- settings:
- goimports:
- local-prefixes:
- - github.com/argoproj/argo-cd/v3
-
-issues:
- max-issues-per-linter: 0
-
- max-same-issues: 0
-
+version: "2"
+run:
+ timeout: 50m
linters:
+ default: none
enable:
+ - errcheck
- errorlint
- gocritic
- - gomodguard
- - importas
+ - govet
+ - ineffassign
- misspell
- perfsprint
- - revive
- staticcheck
- testifylint
- thelper
- unparam
+ - unused
- usestdlibvars
- - usetesting
- whitespace
-
- exclusions:
- rules:
- - linters:
- - unparam
- path: (.+)_test\.go
-
- presets:
- - comments
- - common-false-positives
- - legacy
- - std-error-handling
-
- warn-unused: true
-
settings:
gocritic:
disabled-checks:
- appendAssign
- assignOp
+ - badCond
+ - commentFormatting
- exitAfterDefer
+ - ifElseChain
- mapKey
+ - singleCaseSwitch
- typeSwitchVar
-
- gomodguard:
- blocked:
- modules:
- - 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
-
- importas:
- alias:
- - pkg: github.com/golang-jwt/jwt/v5
- alias: jwtgo
-
- - pkg: k8s.io/api/apps/v1
- alias: appsv1
-
- - pkg: k8s.io/api/core/v1
- alias: corev1
-
- - pkg: k8s.io/api/rbac/v1
- alias: rbacv1
-
- - pkg: k8s.io/apimachinery/pkg/api/errors
- alias: apierrors
-
- - pkg: k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1
- alias: apiextensionsv1
-
- - pkg: k8s.io/apimachinery/pkg/apis/meta/v1
- alias: metav1
-
- - pkg: k8s.io/client-go/informers/core/v1
- alias: informersv1
-
- - pkg: errors
- alias: stderrors
-
- - pkg: github.com/argoproj/argo-cd/v3/util/io
- alias: utilio
-
- nolintlint:
- require-specific: true
-
perfsprint:
- # Optimizes even if it requires an int or uint type cast.
int-conversion: true
- # Optimizes into `err.Error()` even if it is only equivalent for non-nil errors.
- err-error: true
- # Optimizes `fmt.Errorf`.
- errorf: true
- # Optimizes `fmt.Sprintf` with only one argument.
+ err-error: false
+ errorf: false
sprintf1: true
- # Optimizes into strings concatenation.
- strconcat: true
-
- revive:
- # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md
- rules:
- - name: bool-literal-in-expr
-
- - name: blank-imports
- disabled: true
-
- - name: context-as-argument
- arguments:
- - allowTypesBefore: '*testing.T,testing.TB'
-
- - name: context-keys-type
- disabled: true
-
- - name: dot-imports
- disabled: true
-
- - name: duplicated-imports
-
- - name: early-return
- arguments:
- - preserveScope
-
- - name: empty-block
- disabled: true
-
- - name: error-naming
- disabled: true
-
- - name: error-return
-
- - name: error-strings
- disabled: true
-
- - name: errorf
-
- - name: identical-branches
-
- - name: if-return
-
- - name: increment-decrement
-
- - name: indent-error-flow
- arguments:
- - preserveScope
-
- - name: modifies-parameter
-
- - name: optimize-operands-order
-
- - name: range
-
- - name: receiver-naming
-
- - name: redefines-builtin-id
- disabled: true
-
- - name: redundant-import-alias
-
- - name: superfluous-else
- arguments:
- - preserveScope
-
- - name: time-equal
-
- - name: time-naming
- disabled: true
-
- - name: unexported-return
- disabled: true
-
- - name: unnecessary-stmt
-
- - name: unreachable-code
-
- - name: unused-parameter
-
- - name: use-any
-
- - name: useless-break
-
- - name: var-declaration
-
- - name: var-naming
- arguments:
- - - ID
- - - VM
- - - skipPackageNameChecks: true
- upperCaseConst: true
-
+ strconcat: false
staticcheck:
checks:
- - all
- - -SA5011
- - -ST1003
- - -ST1016
-
+ - "all"
+ - "-ST1001" # dot imports are discouraged
+ - "-ST1003" # poorly chosen identifier
+ - "-ST1005" # incorrectly formatted error string
+ - "-ST1011" # poorly chosen name for variable of type time.Duration
+ - "-ST1012" # poorly chosen name for an error variable
+ - "-ST1016" # use consistent method receiver names
+ - "-ST1017" # don't use Yoda conditions
+ - "-ST1019" # importing the same package multiple times
+ - "-ST1023" # redundant type in variable declaration
+ - "-QF1001" # apply De Morgan’s law
+ - "-QF1003" # convert if/else-if chain to tagged switch
+ - "-QF1006" # lift if+break into loop condition
+ - "-QF1007" # merge conditional assignment into variable declaration
+ - "-QF1008" # omit embedded fields from selector expression
+ - "-QF1009" # use time.Time.Equal instead of == operator
+ - "-QF1011" # omit redundant type from variable declaration
+ - "-QF1012" # use fmt.Fprintf(x, ...) instead of x.Write(fmt.Sprintf(...))
testifylint:
enable-all: true
-
disable:
- go-require
-
- usetesting:
- os-mkdir-temp: false
-
-output:
- show-stats: false
-
-version: "2"
+ - equal-values
+ - empty
+ - len
+ - expected-actual
+ - formatter
+ exclusions:
+ generated: lax
+ presets:
+ - comments
+ - common-false-positives
+ - legacy
+ - std-error-handling
+ rules:
+ - linters:
+ - unparam
+ path: (.+)_test\.go
+ - path: (.+)\.go$
+ text: SA5011
+ paths:
+ - third_party$
+ - builtin$
+ - examples$
+issues:
+ max-issues-per-linter: 0
+ max-same-issues: 0
+formatters:
+ enable:
+ - gofumpt
+ - goimports
+ settings:
+ goimports:
+ local-prefixes:
+ - github.com/argoproj/argo-cd/v2
+ exclusions:
+ generated: lax
+ paths:
+ - third_party$
+ - builtin$
+ - examples$
diff --git a/.goreleaser.yaml b/.goreleaser.yaml
index baa7b1f5fa..ad23b85259 100644
--- a/.goreleaser.yaml
+++ b/.goreleaser.yaml
@@ -16,11 +16,11 @@ builds:
flags:
- -v
ldflags:
- - -X github.com/argoproj/argo-cd/v3/common.version={{ .Version }}
- - -X github.com/argoproj/argo-cd/v3/common.buildDate={{ .Date }}
- - -X github.com/argoproj/argo-cd/v3/common.gitCommit={{ .FullCommit }}
- - -X github.com/argoproj/argo-cd/v3/common.gitTreeState={{ .Env.GIT_TREE_STATE }}
- - -X github.com/argoproj/argo-cd/v3/common.kubectlVersion={{ .Env.KUBECTL_VERSION }}
+ - -X github.com/argoproj/argo-cd/v2/common.version={{ .Version }}
+ - -X github.com/argoproj/argo-cd/v2/common.buildDate={{ .Date }}
+ - -X github.com/argoproj/argo-cd/v2/common.gitCommit={{ .FullCommit }}
+ - -X github.com/argoproj/argo-cd/v2/common.gitTreeState={{ .Env.GIT_TREE_STATE }}
+ - -X github.com/argoproj/argo-cd/v2/common.kubectlVersion={{ .Env.KUBECTL_VERSION }}
- -extldflags="-static"
goos:
- linux
@@ -45,11 +45,11 @@ builds:
archives:
- id: argocd-archive
- ids:
- - argocd-cli
+ builds:
+ - argocd-cli
name_template: |-
{{ .ProjectName }}-{{ .Os }}-{{ .Arch }}
- formats: [binary]
+ format: binary
checksum:
name_template: 'cli_checksums.txt'
@@ -79,28 +79,25 @@ release:
All Argo CD container images are signed by cosign. A Provenance is generated for container images and CLI binaries which meet the SLSA Level 3 specifications. See the [documentation](https://argo-cd.readthedocs.io/en/stable/operator-manual/signed-release-assets) on how to verify.
- ## Release Notes Blog Post
- For a detailed breakdown of the key changes and improvements in this release, check out the [official blog post](https://blog.argoproj.io/argo-cd-v2-14-release-candidate-57a664791e2a)
## Upgrading
If upgrading from a different minor version, be sure to read the [upgrading](https://argo-cd.readthedocs.io/en/stable/operator-manual/upgrading/overview/) documentation.
footer: |
**Full Changelog**: https://github.com/argoproj/argo-cd/compare/{{ .PreviousTag }}...{{ .Tag }}
-
+
+
snapshot: #### To be removed for PR
- version_template: '2.6.0'
+ name_template: "2.6.0"
changelog:
- use: github
+ use:
+ github
sort: asc
abbrev: 0
groups: # Regex use RE2 syntax as defined here: https://github.com/google/re2/wiki/Syntax.
- - title: 'Breaking Changes'
- regexp: '^.*?(\([[:word:]]+\))??!:.+$'
- order: 0
- title: 'Features'
regexp: '^.*?feat(\([[:word:]]+\))??!?:.+$'
order: 100
@@ -120,4 +117,7 @@ changelog:
- '^test:'
- '^.*?Bump(\([[:word:]]+\))?.+$'
- '^.*?\[Bot\](\([[:word:]]+\))?.+$'
+
+
# yaml-language-server: $schema=https://goreleaser.com/static/schema.json
+
diff --git a/.mockery.yaml b/.mockery.yaml
index ca4a28b745..de7e1266f4 100644
--- a/.mockery.yaml
+++ b/.mockery.yaml
@@ -1,82 +1,79 @@
-dir: '{{.InterfaceDir}}/mocks'
-structname: '{{.InterfaceName}}'
-filename: '{{.InterfaceName}}.go'
-pkgname: mocks
-
-template-data:
- unroll-variadic: true
-
+# global config
+filename: "{{.InterfaceName}}.go"
+dir: "{{.InterfaceDir}}/mocks"
+outpkg: "mocks"
+mockname: "{{.InterfaceName}}"
+with-expecter: false
+# individual interface config
packages:
- github.com/argoproj/argo-cd/v3/applicationset/generators:
+ github.com/argoproj/argo-cd/v2/applicationset/generators:
interfaces:
- Generator: {}
- github.com/argoproj/argo-cd/v3/applicationset/services:
+ Generator:
+ github.com/argoproj/argo-cd/v2/applicationset/services:
interfaces:
- Repos: {}
- github.com/argoproj/argo-cd/v3/applicationset/services/scm_provider:
+ Repos:
+ github.com/argoproj/argo-cd/v2/applicationset/services/scm_provider:
config:
- dir: applicationset/services/scm_provider/aws_codecommit/mocks
+ dir: "applicationset/services/scm_provider/aws_codecommit/mocks"
interfaces:
- AWSCodeCommitClient: {}
- AWSTaggingClient: {}
- github.com/argoproj/argo-cd/v3/applicationset/utils:
- interfaces:
- Renderer: {}
- github.com/argoproj/argo-cd/v3/commitserver/apiclient:
- interfaces:
- Clientset: {}
- CommitServiceClient: {}
- github.com/argoproj/argo-cd/v3/commitserver/commit:
- interfaces:
- RepoClientFactory: {}
- github.com/argoproj/argo-cd/v3/controller/cache:
- interfaces:
- LiveStateCache: {}
- github.com/argoproj/argo-cd/v3/pkg/apiclient/cluster:
- interfaces:
- ClusterServiceServer: {}
- github.com/argoproj/argo-cd/v3/pkg/apiclient/session:
- interfaces:
- SessionServiceClient: {}
- SessionServiceServer: {}
- github.com/argoproj/argo-cd/v3/pkg/client/clientset/versioned/typed/application/v1alpha1:
- interfaces:
- AppProjectInterface: {}
- github.com/argoproj/argo-cd/v3/reposerver/apiclient:
- interfaces:
- RepoServerService_GenerateManifestWithFilesClient: {}
- RepoServerServiceClient: {}
- github.com/argoproj/argo-cd/v3/server/application:
- interfaces:
- Broadcaster: {}
- github.com/argoproj/argo-cd/v3/server/extension:
- interfaces:
- ApplicationGetter: {}
- ExtensionMetricsRegistry: {}
- ProjectGetter: {}
- RbacEnforcer: {}
- SettingsGetter: {}
- UserGetter: {}
- github.com/argoproj/argo-cd/v3/util/db:
- interfaces:
- ArgoDB: {}
- github.com/argoproj/argo-cd/v3/util/git:
- interfaces:
- Client: {}
- github.com/argoproj/argo-cd/v3/util/helm:
- interfaces:
- Client: {}
- github.com/argoproj/argo-cd/v3/util/io:
- interfaces:
- TempPaths: {}
- github.com/argoproj/argo-cd/v3/util/notification/argocd:
- interfaces:
- Service: {}
- github.com/argoproj/argo-cd/v3/util/workloadidentity:
- interfaces:
- TokenProvider: {}
- github.com/microsoft/azure-devops-go-api/azuredevops/v7/git:
+ AWSCodeCommitClient:
+ AWSTaggingClient:
+ github.com/microsoft/azure-devops-go-api/azuredevops/git:
config:
- dir: applicationset/services/scm_provider/azure_devops/git/mocks
+ dir: "applicationset/services/scm_provider/azure_devops/git/mocks"
interfaces:
- Client: {}
+ Client:
+ github.com/argoproj/argo-cd/v2/applicationset/utils:
+ interfaces:
+ Renderer:
+ github.com/argoproj/argo-cd/v2/commitserver/commit:
+ interfaces:
+ RepoClientFactory:
+ github.com/argoproj/argo-cd/v2/commitserver/apiclient:
+ interfaces:
+ CommitServiceClient:
+ Clientset:
+ github.com/argoproj/argo-cd/v2/controller/cache:
+ interfaces:
+ LiveStateCache:
+ github.com/argoproj/argo-cd/v2/reposerver/apiclient:
+ interfaces:
+ RepoServerServiceClient:
+ RepoServerService_GenerateManifestWithFilesClient:
+ github.com/argoproj/argo-cd/v2/server/application:
+ interfaces:
+ Broadcaster:
+ github.com/argoproj/argo-cd/v2/server/extension:
+ interfaces:
+ ApplicationGetter:
+ ExtensionMetricsRegistry:
+ ProjectGetter:
+ RbacEnforcer:
+ SettingsGetter:
+ UserGetter:
+ github.com/argoproj/argo-cd/v2/util/db:
+ interfaces:
+ ArgoDB:
+ github.com/argoproj/argo-cd/v2/util/git:
+ interfaces:
+ Client:
+ github.com/argoproj/argo-cd/v2/util/helm:
+ interfaces:
+ Client:
+ github.com/argoproj/argo-cd/v2/util/io:
+ interfaces:
+ TempPaths:
+ github.com/argoproj/argo-cd/v2/util/notification/argocd:
+ interfaces:
+ Service:
+ # These mocks are not currently used, but they are part of the public API of this package.
+ github.com/argoproj/argo-cd/v2/pkg/apiclient/session:
+ interfaces:
+ SessionServiceServer:
+ SessionServiceClient:
+ github.com/argoproj/argo-cd/v2/pkg/apiclient/cluster:
+ interfaces:
+ ClusterServiceServer:
+ github.com/argoproj/argo-cd/v2/pkg/client/clientset/versioned/typed/application/v1alpha1:
+ interfaces:
+ AppProjectInterface:
diff --git a/Dockerfile b/Dockerfile
index 789283a40f..d2b3eedc5d 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -1,12 +1,10 @@
-ARG BASE_IMAGE=docker.io/library/ubuntu:24.04@sha256:80dd3c3b9c6cecb9f1667e9290b3bc61b78c2678c02cbdae5f0fea92cc6734ab
+ARG BASE_IMAGE=docker.io/library/ubuntu:24.04@sha256:3f85b7caad41a95462cf5b787d8a04604c8262cdcdf9a472b8c52ef83375fe15
####################################################################################################
# Builder image
# Initial stage which pulls prepares build dependencies and CLI tooling we need for our final image
# Also used as the image in CI jobs so needs all dependencies
####################################################################################################
-FROM docker.io/library/golang:1.24.3@sha256:86b4cff66e04d41821a17cea30c1031ed53e2635e2be99ae0b4a7d69336b5063 AS builder
-
-WORKDIR /tmp
+FROM docker.io/library/golang:1.24.4@sha256:db5d0afbfb4ab648af2393b92e87eaae9ad5e01132803d80caef91b5752d289c AS builder
RUN echo 'deb http://archive.debian.org/debian buster-backports main' >> /etc/apt/sources.list
@@ -25,6 +23,8 @@ RUN apt-get update && apt-get install --no-install-recommends -y \
apt-get clean && \
rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
+WORKDIR /tmp
+
COPY hack/install.sh hack/tool-versions.sh ./
COPY hack/installers installers
@@ -40,8 +40,8 @@ LABEL org.opencontainers.image.source="https://github.com/argoproj/argo-cd"
USER root
-ENV ARGOCD_USER_ID=999 \
- DEBIAN_FRONTEND=noninteractive
+ENV ARGOCD_USER_ID=999
+ENV DEBIAN_FRONTEND=noninteractive
RUN groupadd -g $ARGOCD_USER_ID argocd && \
useradd -r -u $ARGOCD_USER_ID -g argocd argocd && \
@@ -55,13 +55,11 @@ RUN groupadd -g $ARGOCD_USER_ID argocd && \
apt-get clean && \
rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
-COPY hack/gpg-wrapper.sh \
- hack/git-verify-wrapper.sh \
- entrypoint.sh \
- /usr/local/bin/
+COPY hack/gpg-wrapper.sh /usr/local/bin/gpg-wrapper.sh
+COPY hack/git-verify-wrapper.sh /usr/local/bin/git-verify-wrapper.sh
COPY --from=builder /usr/local/bin/helm /usr/local/bin/helm
COPY --from=builder /usr/local/bin/kustomize /usr/local/bin/kustomize
-
+COPY entrypoint.sh /usr/local/bin/entrypoint.sh
# keep uid_entrypoint.sh for backward compatibility
RUN ln -s /usr/local/bin/entrypoint.sh /usr/local/bin/uid_entrypoint.sh
@@ -103,7 +101,7 @@ RUN HOST_ARCH=$TARGETARCH NODE_ENV='production' NODE_ONLINE_ENV='online' NODE_OP
####################################################################################################
# Argo CD Build stage which performs the actual build of Argo CD binaries
####################################################################################################
-FROM --platform=$BUILDPLATFORM docker.io/library/golang:1.24.3@sha256:86b4cff66e04d41821a17cea30c1031ed53e2635e2be99ae0b4a7d69336b5063 AS argocd-build
+FROM --platform=$BUILDPLATFORM docker.io/library/golang:1.24.4@sha256:db5d0afbfb4ab648af2393b92e87eaae9ad5e01132803d80caef91b5752d289c AS argocd-build
WORKDIR /go/src/github.com/argoproj/argo-cd
@@ -113,13 +111,13 @@ RUN go mod download
# Perform the build
COPY . .
COPY --from=argocd-ui /src/dist/app /go/src/github.com/argoproj/argo-cd/ui/dist/app
-ARG TARGETOS \
- TARGETARCH
+ARG TARGETOS
+ARG TARGETARCH
# These build args are optional; if not specified the defaults will be taken from the Makefile
-ARG GIT_TAG \
- BUILD_DATE \
- GIT_TREE_STATE \
- GIT_COMMIT
+ARG GIT_TAG
+ARG BUILD_DATE
+ARG GIT_TREE_STATE
+ARG GIT_COMMIT
RUN GIT_COMMIT=$GIT_COMMIT \
GIT_TREE_STATE=$GIT_TREE_STATE \
GIT_TAG=$GIT_TAG \
@@ -132,7 +130,6 @@ RUN GIT_COMMIT=$GIT_COMMIT \
# Final image
####################################################################################################
FROM argocd-base
-ENTRYPOINT ["/usr/bin/tini", "--"]
COPY --from=argocd-build /go/src/github.com/argoproj/argo-cd/dist/argocd* /usr/local/bin/
USER root
@@ -147,3 +144,4 @@ RUN ln -s /usr/local/bin/argocd /usr/local/bin/argocd-server && \
ln -s /usr/local/bin/argocd /usr/local/bin/argocd-commit-server
USER $ARGOCD_USER_ID
+ENTRYPOINT ["/usr/bin/tini", "--"]
diff --git a/Makefile b/Makefile
index 7fe09815f1..8cc1b928da 100644
--- a/Makefile
+++ b/Makefile
@@ -1,11 +1,9 @@
-PACKAGE=github.com/argoproj/argo-cd/v3/common
+PACKAGE=github.com/argoproj/argo-cd/v2/common
CURRENT_DIR=$(shell pwd)
DIST_DIR=${CURRENT_DIR}/dist
CLI_NAME=argocd
BIN_NAME=argocd
-
-# When using OSX/Darwin, you might need to enable CGO for local builds
-CGO_FLAG?=0
+CGO_FLAG=0
GEN_RESOURCES_CLI_NAME=argocd-resources-gen
@@ -357,6 +355,11 @@ mod-vendor: test-tools-image
mod-vendor-local: mod-download-local
go mod vendor
+# Deprecated - replace by install-tools-local
+.PHONY: install-lint-tools
+install-lint-tools:
+ ./hack/install.sh lint-tools
+
# Run linter on the code
.PHONY: lint
lint: test-tools-image
@@ -432,7 +435,7 @@ test-e2e:
test-e2e-local: cli-local
# NO_PROXY ensures all tests don't go out through a proxy if one is configured on the test system
export GO111MODULE=off
- DIST_DIR=${DIST_DIR} RERUN_FAILS=5 PACKAGES="./test/e2e" ARGOCD_E2E_RECORD=${ARGOCD_E2E_RECORD} ARGOCD_CONFIG_DIR=$(HOME)/.config/argocd-e2e ARGOCD_GPG_ENABLED=true NO_PROXY=* ./hack/test.sh -timeout $(ARGOCD_E2E_TEST_TIMEOUT) -v -args -test.gocoverdir="$(PWD)/test-results"
+ DIST_DIR=${DIST_DIR} RERUN_FAILS=5 PACKAGES="./test/e2e" ARGOCD_E2E_RECORD=${ARGOCD_E2E_RECORD} ARGOCD_GPG_ENABLED=true NO_PROXY=* ./hack/test.sh -timeout $(ARGOCD_E2E_TEST_TIMEOUT) -v -args -test.gocoverdir="$(PWD)/test-results"
# Spawns a shell in the test server container for debugging purposes
debug-test-server: test-tools-image
@@ -488,7 +491,6 @@ start-e2e-local: mod-vendor-local dep-ui-local cli-local
ARGOCD_APPLICATIONSET_CONTROLLER_ALLOWED_SCM_PROVIDERS=http://127.0.0.1:8341,http://127.0.0.1:8342,http://127.0.0.1:8343,http://127.0.0.1:8344 \
ARGOCD_E2E_TEST=true \
ARGOCD_HYDRATOR_ENABLED=true \
- ARGOCD_CLUSTER_CACHE_EVENTS_PROCESSING_INTERVAL=1ms \
goreman -f $(ARGOCD_PROCFILE) start ${ARGOCD_START}
ls -lrt /tmp/coverage
@@ -597,7 +599,6 @@ install-codegen-tools-local:
.PHONY: install-go-tools-local
install-go-tools-local:
./hack/install.sh codegen-go-tools
- ./hack/install.sh lint-tools
.PHONY: dep-ui
dep-ui: test-tools-image
@@ -678,6 +679,7 @@ help:
@echo 'debug:'
@echo ' list -- list all make targets'
@echo ' install-tools-local -- install all the tools below'
+ @echo ' install-lint-tools(-local)'
@echo
@echo 'codegen:'
@echo ' codegen(-local) -- if using -local, run the following targets first'
diff --git a/Procfile b/Procfile
index e748770659..9ff5e67236 100644
--- a/Procfile
+++ b/Procfile
@@ -1,6 +1,6 @@
controller: [ "$BIN_MODE" = 'true' ] && COMMAND=./dist/argocd || COMMAND='go run ./cmd/main.go' && sh -c "GOCOVERDIR=${ARGOCD_COVERAGE_DIR:-/tmp/coverage/app-controller} HOSTNAME=testappcontroller-1 FORCE_LOG_COLORS=1 ARGOCD_FAKE_IN_CLUSTER=true ARGOCD_TLS_DATA_PATH=${ARGOCD_TLS_DATA_PATH:-/tmp/argocd-local/tls} ARGOCD_SSH_DATA_PATH=${ARGOCD_SSH_DATA_PATH:-/tmp/argocd-local/ssh} ARGOCD_BINARY_NAME=argocd-application-controller $COMMAND --loglevel debug --redis localhost:${ARGOCD_E2E_REDIS_PORT:-6379} --repo-server localhost:${ARGOCD_E2E_REPOSERVER_PORT:-8081} --commit-server localhost:${ARGOCD_E2E_COMMITSERVER_PORT:-8086} --otlp-address=${ARGOCD_OTLP_ADDRESS} --application-namespaces=${ARGOCD_APPLICATION_NAMESPACES:-''} --server-side-diff-enabled=${ARGOCD_APPLICATION_CONTROLLER_SERVER_SIDE_DIFF:-'false'} --hydrator-enabled=${ARGOCD_HYDRATOR_ENABLED:='false'}"
api-server: [ "$BIN_MODE" = 'true' ] && COMMAND=./dist/argocd || COMMAND='go run ./cmd/main.go' && sh -c "GOCOVERDIR=${ARGOCD_COVERAGE_DIR:-/tmp/coverage/api-server} FORCE_LOG_COLORS=1 ARGOCD_FAKE_IN_CLUSTER=true ARGOCD_TLS_DATA_PATH=${ARGOCD_TLS_DATA_PATH:-/tmp/argocd-local/tls} ARGOCD_SSH_DATA_PATH=${ARGOCD_SSH_DATA_PATH:-/tmp/argocd-local/ssh} ARGOCD_BINARY_NAME=argocd-server $COMMAND --loglevel debug --redis localhost:${ARGOCD_E2E_REDIS_PORT:-6379} --disable-auth=${ARGOCD_E2E_DISABLE_AUTH:-'true'} --insecure --dex-server http://localhost:${ARGOCD_E2E_DEX_PORT:-5556} --repo-server localhost:${ARGOCD_E2E_REPOSERVER_PORT:-8081} --port ${ARGOCD_E2E_APISERVER_PORT:-8080} --otlp-address=${ARGOCD_OTLP_ADDRESS} --application-namespaces=${ARGOCD_APPLICATION_NAMESPACES:-''} --hydrator-enabled=${ARGOCD_HYDRATOR_ENABLED:='false'}"
-dex: sh -c "ARGOCD_BINARY_NAME=argocd-dex go run github.com/argoproj/argo-cd/v3/cmd gendexcfg -o `pwd`/dist/dex.yaml && (test -f dist/dex.yaml || { echo 'Failed to generate dex configuration'; exit 1; }) && docker run --rm -p ${ARGOCD_E2E_DEX_PORT:-5556}:${ARGOCD_E2E_DEX_PORT:-5556} -v `pwd`/dist/dex.yaml:/dex.yaml ghcr.io/dexidp/dex:$(grep "image: ghcr.io/dexidp/dex" manifests/base/dex/argocd-dex-server-deployment.yaml | cut -d':' -f3) dex serve /dex.yaml"
+dex: sh -c "ARGOCD_BINARY_NAME=argocd-dex go run github.com/argoproj/argo-cd/v2/cmd gendexcfg -o `pwd`/dist/dex.yaml && (test -f dist/dex.yaml || { echo 'Failed to generate dex configuration'; exit 1; }) && docker run --rm -p ${ARGOCD_E2E_DEX_PORT:-5556}:${ARGOCD_E2E_DEX_PORT:-5556} -v `pwd`/dist/dex.yaml:/dex.yaml ghcr.io/dexidp/dex:$(grep "image: ghcr.io/dexidp/dex" manifests/base/dex/argocd-dex-server-deployment.yaml | cut -d':' -f3) dex serve /dex.yaml"
redis: hack/start-redis-with-password.sh
repo-server: [ "$BIN_MODE" = 'true' ] && COMMAND=./dist/argocd || COMMAND='go run ./cmd/main.go' && sh -c "GOCOVERDIR=${ARGOCD_COVERAGE_DIR:-/tmp/coverage/repo-server} FORCE_LOG_COLORS=1 ARGOCD_FAKE_IN_CLUSTER=true ARGOCD_GNUPGHOME=${ARGOCD_GNUPGHOME:-/tmp/argocd-local/gpg/keys} ARGOCD_PLUGINSOCKFILEPATH=${ARGOCD_PLUGINSOCKFILEPATH:-./test/cmp} ARGOCD_GPG_DATA_PATH=${ARGOCD_GPG_DATA_PATH:-/tmp/argocd-local/gpg/source} ARGOCD_TLS_DATA_PATH=${ARGOCD_TLS_DATA_PATH:-/tmp/argocd-local/tls} ARGOCD_SSH_DATA_PATH=${ARGOCD_SSH_DATA_PATH:-/tmp/argocd-local/ssh} ARGOCD_BINARY_NAME=argocd-repo-server ARGOCD_GPG_ENABLED=${ARGOCD_GPG_ENABLED:-false} $COMMAND --loglevel debug --port ${ARGOCD_E2E_REPOSERVER_PORT:-8081} --redis localhost:${ARGOCD_E2E_REDIS_PORT:-6379} --otlp-address=${ARGOCD_OTLP_ADDRESS}"
cmp-server: [ "$ARGOCD_E2E_TEST" = 'true' ] && exit 0 || [ "$BIN_MODE" = 'true' ] && COMMAND=./dist/argocd || COMMAND='go run ./cmd/main.go' && sh -c "FORCE_LOG_COLORS=1 ARGOCD_FAKE_IN_CLUSTER=true ARGOCD_BINARY_NAME=argocd-cmp-server ARGOCD_PLUGINSOCKFILEPATH=${ARGOCD_PLUGINSOCKFILEPATH:-./test/cmp} $COMMAND --config-dir-path ./test/cmp --loglevel debug --otlp-address=${ARGOCD_OTLP_ADDRESS}"
diff --git a/SECURITY-INSIGHTS.yml b/SECURITY-INSIGHTS.yml
index 9af8b173d7..74236df3b1 100644
--- a/SECURITY-INSIGHTS.yml
+++ b/SECURITY-INSIGHTS.yml
@@ -3,9 +3,9 @@ header:
expiration-date: '2024-10-31T00:00:00.000Z' # One year from initial release.
last-updated: '2023-10-27'
last-reviewed: '2023-10-27'
- commit-hash: 226a670fe6b3c6769ff6d18e6839298a58e4577d
+ commit-hash: 74a367d10e7110209610ba3ec225539ebe5f7522
project-url: https://github.com/argoproj/argo-cd
- project-release: v3.1.0
+ project-release: v2.14.0
changelog: https://github.com/argoproj/argo-cd/releases
license: https://github.com/argoproj/argo-cd/blob/master/LICENSE
project-lifecycle:
diff --git a/USERS.md b/USERS.md
index 9ef7bced2d..ef200ecb3a 100644
--- a/USERS.md
+++ b/USERS.md
@@ -30,8 +30,7 @@ Currently, the following organizations are **officially** using Argo CD:
1. [Ant Group](https://www.antgroup.com/)
1. [AppDirect](https://www.appdirect.com)
1. [Arctiq Inc.](https://www.arctiq.ca)
-1. [Artemis Health by Nomi Health] (https://www.artemishealth.com/)
-1. [Arturia](https://www.arturia.com)
+2. [Arturia](https://www.arturia.com)
1. [ARZ Allgemeines Rechenzentrum GmbH](https://www.arz.at/)
1. [Augury](https://www.augury.com/)
1. [Autodesk](https://www.autodesk.com)
@@ -46,7 +45,6 @@ Currently, the following organizations are **officially** using Argo CD:
1. [Bedag Informatik AG](https://www.bedag.ch/)
1. [Beleza Na Web](https://www.belezanaweb.com.br/)
1. [Believable Bots](https://believablebots.io)
-1. [Bayer AG](https://bayer.com)
1. [BigPanda](https://bigpanda.io)
1. [BioBox Analytics](https://biobox.io)
1. [BMW Group](https://www.bmwgroup.com/)
@@ -69,7 +67,6 @@ Currently, the following organizations are **officially** using Argo CD:
1. [Chainnodes](https://chainnodes.org)
1. [Chargetrip](https://chargetrip.com)
1. [Chime](https://www.chime.com)
-1. [Chronicle Labs](https://chroniclelabs.org)
1. [Cisco ET&I](https://eti.cisco.com/)
1. [Cloud Posse](https://www.cloudposse.com/)
1. [Cloud Scale](https://cloudscaleinc.com/)
@@ -95,15 +92,11 @@ Currently, the following organizations are **officially** using Argo CD:
1. [Daydream](https://daydream.ing)
1. [Deloitte](https://www.deloitte.com/)
1. [Deutsche Telekom AG](https://telekom.com)
-1. [Deutsche Bank AG](https://www.deutsche-bank.de/)
1. [Devopsi - Poland Software/DevOps Consulting](https://devopsi.pl/)
1. [Devtron Labs](https://github.com/devtron-labs/devtron)
-1. [DigitalEd](https://www.digitaled.com)
1. [DigitalOcean](https://www.digitalocean.com)
-1. [Divar](https://divar.ir)
1. [Divistant](https://divistant.com)
1. [Dott](https://ridedott.com)
-1. [Doubble](https://www.doubble.app)
1. [Doximity](https://www.doximity.com/)
1. [EDF Renewables](https://www.edf-re.com/)
1. [edX](https://edx.org)
@@ -153,7 +146,6 @@ Currently, the following organizations are **officially** using Argo CD:
1. [Hazelcast](https://hazelcast.com/)
1. [Healy](https://www.healyworld.net)
1. [Helio](https://helio.exchange)
-1. [hetao101](https://www.hetao101.com/)
1. [Hetki](https://hetki.ai)
1. [hipages](https://hipages.com.au/)
1. [Hiya](https://hiya.com)
@@ -162,7 +154,6 @@ Currently, the following organizations are **officially** using Argo CD:
1. [IABAI](https://www.iab.ai)
1. [IBM](https://www.ibm.com/)
1. [Ibotta](https://home.ibotta.com)
-1. [Icelandair](https://www.icelandair.com)
1. [IFS](https://www.ifs.com)
1. [IITS-Consulting](https://iits-consulting.de)
1. [IllumiDesk](https://www.illumidesk.com)
@@ -200,10 +191,10 @@ Currently, the following organizations are **officially** using Argo CD:
1. [Lian Chu Securities](https://lczq.com)
1. [Liatrio](https://www.liatrio.com)
1. [Lightricks](https://www.lightricks.com/)
+1. [LINE](https://linecorp.com/en/)
1. [Loom](https://www.loom.com/)
1. [Lucid Motors](https://www.lucidmotors.com/)
1. [Lytt](https://www.lytt.co/)
-1. [LY Corporation](https://www.lycorp.co.jp/en/)
1. [Magic Leap](https://www.magicleap.com/)
1. [Majid Al Futtaim](https://www.majidalfuttaim.com/)
1. [Major League Baseball](https://mlb.com)
@@ -266,7 +257,6 @@ Currently, the following organizations are **officially** using Argo CD:
1. [Patreon](https://www.patreon.com/)
1. [PayIt](https://payitgov.com/)
1. [PayPay](https://paypay.ne.jp/)
-1. [Paystack](https://paystack.com/)
1. [Peloton Interactive](https://www.onepeloton.com/)
1. [Percona](https://percona.com/)
1. [PGS](https://www.pgs.com)
@@ -278,7 +268,6 @@ Currently, the following organizations are **officially** using Argo CD:
1. [PITS Globale Datenrettungsdienste](https://www.pitsdatenrettung.de/)
1. [Platform9 Systems](https://platform9.com/)
1. [Polarpoint.io](https://polarpoint.io)
-1. [Pollinate](https://www.pollinate.global)
1. [PostFinance](https://github.com/postfinance)
1. [Preferred Networks](https://preferred.jp/en/)
1. [Previder BV](https://previder.nl)
@@ -313,7 +302,6 @@ Currently, the following organizations are **officially** using Argo CD:
1. [Saloodo! GmbH](https://www.saloodo.com)
1. [Sap Labs](http://sap.com)
1. [Sauce Labs](https://saucelabs.com/)
-1. [Schneider Electric](https://www.se.com)
1. [Schwarz IT](https://jobs.schwarz/it-mission)
1. [SCRM Lidl International Hub](https://scrm.lidl)
1. [SEEK](https://seek.com.au)
@@ -323,7 +311,7 @@ Currently, the following organizations are **officially** using Argo CD:
1. [SI Analytics](https://si-analytics.ai)
1. [Sidewalk Entertainment](https://sidewalkplay.com/)
1. [Skit](https://skit.ai/)
-1. [Skribble](https://skribble.com)
+1. [Skribble](https://skribble.com)
1. [Skyscanner](https://www.skyscanner.net/)
1. [Smart Pension](https://www.smartpension.co.uk/)
1. [Smilee.io](https://smilee.io)
@@ -344,13 +332,11 @@ Currently, the following organizations are **officially** using Argo CD:
1. [Sumo Logic](https://sumologic.com/)
1. [Sutpc](http://www.sutpc.com/)
1. [Swiss Post](https://github.com/swisspost)
-1. [Swissblock Technologies](https://swissblock.net/)
1. [Swisscom](https://www.swisscom.ch)
1. [Swissquote](https://github.com/swissquote)
1. [Syncier](https://syncier.com/)
1. [Synergy](https://synergy.net.au)
1. [Syself](https://syself.com)
-1. [T-ROC Global](https://trocglobal.com/)
1. [TableCheck](https://tablecheck.com/)
1. [Tailor Brands](https://www.tailorbrands.com)
1. [Tamkeen Technologies](https://tamkeentech.sa/)
@@ -388,11 +374,9 @@ Currently, the following organizations are **officially** using Argo CD:
1. [Vinted](https://vinted.com/)
1. [Virtuo](https://www.govirtuo.com/)
1. [VISITS Technologies](https://visits.world/en)
-1. [Viya](https://viya.me)
1. [Volvo Cars](https://www.volvocars.com/)
1. [Voyager Digital](https://www.investvoyager.com/)
1. [VSHN - The DevOps Company](https://vshn.ch/)
-1. [Wakacje.pl](https://www.wakacje.pl/)
1. [Walkbase](https://www.walkbase.com/)
1. [Webstores](https://www.webstores.nl)
1. [Wehkamp](https://www.wehkamp.nl/)
@@ -404,12 +388,10 @@ Currently, the following organizations are **officially** using Argo CD:
1. [WooliesX](https://wooliesx.com.au/)
1. [Woolworths Group](https://www.woolworthsgroup.com.au/)
1. [WSpot](https://www.wspot.com.br/)
-1. [X3M ads](https://x3mads.com)
1. [Yieldlab](https://www.yieldlab.de/)
1. [Youverify](https://youverify.co/)
1. [Yubo](https://www.yubo.live/)
-1. [Yuno](https://y.uno/)
1. [ZDF](https://www.zdf.de/)
1. [Zimpler](https://www.zimpler.com/)
-1. [ZipRecruiter](https://www.ziprecruiter.com/)
+1. [ZipRecuiter](https://www.ziprecruiter.com/)
1. [ZOZO](https://corp.zozo.com/)
diff --git a/VERSION b/VERSION
index fd2a01863f..ecbbf82074 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-3.1.0
+2.14.15
diff --git a/applicationset/controllers/applicationset_controller.go b/applicationset/controllers/applicationset_controller.go
index 9d6184cea8..ac5b1975b0 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"
- apierrors "k8s.io/apimachinery/pkg/api/errors"
+ apierr "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
@@ -45,20 +45,19 @@ import (
"sigs.k8s.io/controller-runtime/pkg/handler"
"sigs.k8s.io/controller-runtime/pkg/predicate"
- "github.com/argoproj/argo-cd/v3/applicationset/controllers/template"
- "github.com/argoproj/argo-cd/v3/applicationset/generators"
- "github.com/argoproj/argo-cd/v3/applicationset/metrics"
- "github.com/argoproj/argo-cd/v3/applicationset/status"
- "github.com/argoproj/argo-cd/v3/applicationset/utils"
- "github.com/argoproj/argo-cd/v3/common"
- applog "github.com/argoproj/argo-cd/v3/util/app/log"
- "github.com/argoproj/argo-cd/v3/util/db"
+ "github.com/argoproj/argo-cd/v2/applicationset/controllers/template"
+ "github.com/argoproj/argo-cd/v2/applicationset/generators"
+ "github.com/argoproj/argo-cd/v2/applicationset/metrics"
+ "github.com/argoproj/argo-cd/v2/applicationset/status"
+ "github.com/argoproj/argo-cd/v2/applicationset/utils"
+ "github.com/argoproj/argo-cd/v2/common"
+ "github.com/argoproj/argo-cd/v2/util/db"
- argov1alpha1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- argoutil "github.com/argoproj/argo-cd/v3/util/argo"
- "github.com/argoproj/argo-cd/v3/util/argo/normalizers"
+ argov1alpha1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+ argoutil "github.com/argoproj/argo-cd/v2/util/argo"
+ "github.com/argoproj/argo-cd/v2/util/argo/normalizers"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application"
)
const (
@@ -468,7 +467,7 @@ func (r *ApplicationSetReconciler) setApplicationSetStatusCondition(ctx context.
updatedAppset.DeepCopyInto(applicationSet)
return nil
})
- if err != nil && !apierrors.IsNotFound(err) {
+ if err != nil && !apierr.IsNotFound(err) {
return fmt.Errorf("unable to set application set condition: %w", err)
}
}
@@ -482,23 +481,24 @@ func (r *ApplicationSetReconciler) validateGeneratedApplications(ctx context.Con
errorsByIndex := map[int]error{}
namesSet := map[string]bool{}
for i, app := range desiredApplications {
- if namesSet[app.Name] {
+ if !namesSet[app.Name] {
+ namesSet[app.Name] = true
+ } else {
errorsByIndex[i] = fmt.Errorf("ApplicationSet %s contains applications with duplicate name: %s", applicationSetInfo.Name, app.Name)
continue
}
- namesSet[app.Name] = true
appProject := &argov1alpha1.AppProject{}
err := r.Get(ctx, types.NamespacedName{Name: app.Spec.Project, Namespace: r.ArgoCDNamespace}, appProject)
if err != nil {
- if apierrors.IsNotFound(err) {
+ if apierr.IsNotFound(err) {
errorsByIndex[i] = fmt.Errorf("application references project %s which does not exist", app.Spec.Project)
continue
}
return nil, err
}
- if _, err = argoutil.GetDestinationCluster(ctx, app.Spec.Destination, r.ArgoDB); err != nil {
+ if err := utils.ValidateDestination(ctx, &app.Spec.Destination, r.KubeClientset, r.ArgoCDNamespace); err != nil {
errorsByIndex[i] = fmt.Errorf("application destination spec is invalid: %s", err.Error())
continue
}
@@ -578,7 +578,7 @@ func (r *ApplicationSetReconciler) createOrUpdateInCluster(ctx context.Context,
var firstError error
// Creates or updates the application in appList
for _, generatedApp := range desiredApplications {
- appLog := logCtx.WithFields(applog.GetAppLogFields(&generatedApp))
+ appLog := logCtx.WithFields(log.Fields{"app": generatedApp.QualifiedName()})
// Normalize to avoid fighting with the application controller.
generatedApp.Spec = *argoutil.NormalizeApplicationSpec(&generatedApp.Spec)
@@ -741,7 +741,7 @@ func (r *ApplicationSetReconciler) deleteInCluster(ctx context.Context, logCtx *
// Delete apps that are not in m[string]bool
var firstError error
for _, app := range current {
- logCtx = logCtx.WithFields(applog.GetAppLogFields(&app))
+ logCtx = logCtx.WithField("app", app.QualifiedName())
_, exists := m[app.Name]
if !exists {
@@ -771,7 +771,7 @@ func (r *ApplicationSetReconciler) deleteInCluster(ctx context.Context, logCtx *
}
// removeFinalizerOnInvalidDestination removes the Argo CD resources finalizer if the application contains an invalid target (eg missing cluster)
-func (r *ApplicationSetReconciler) removeFinalizerOnInvalidDestination(ctx context.Context, applicationSet argov1alpha1.ApplicationSet, app *argov1alpha1.Application, clusterList []utils.ClusterSpecifier, appLog *log.Entry) error {
+func (r *ApplicationSetReconciler) removeFinalizerOnInvalidDestination(ctx context.Context, applicationSet argov1alpha1.ApplicationSet, app *argov1alpha1.Application, clusterList *argov1alpha1.ClusterList, appLog *log.Entry) error {
// Only check if the finalizers need to be removed IF there are finalizers to remove
if len(app.Finalizers) == 0 {
return nil
@@ -780,18 +780,21 @@ func (r *ApplicationSetReconciler) removeFinalizerOnInvalidDestination(ctx conte
var validDestination bool
// Detect if the destination is invalid (name doesn't correspond to a matching cluster)
- if destCluster, err := argoutil.GetDestinationCluster(ctx, app.Spec.Destination, r.ArgoDB); err != nil {
+ if err := utils.ValidateDestination(ctx, &app.Spec.Destination, r.KubeClientset, r.ArgoCDNamespace); err != nil {
appLog.Warnf("The destination cluster for %s couldn't be found: %v", app.Name, err)
validDestination = false
} else {
// Detect if the destination's server field does not match an existing cluster
+
matchingCluster := false
- for _, cluster := range clusterList {
- if destCluster.Server != cluster.Server {
+ for _, cluster := range clusterList.Items {
+ // Server fields must match. Note that ValidateDestination ensures that the server field is set, if applicable.
+ if app.Spec.Destination.Server != cluster.Server {
continue
}
- if destCluster.Name != cluster.Name {
+ // The name must match, if it is not empty
+ if app.Spec.Destination.Name != "" && cluster.Name != app.Spec.Destination.Name {
continue
}
@@ -976,16 +979,17 @@ func (r *ApplicationSetReconciler) buildAppSyncMap(applicationSet argov1alpha1.A
}
appStatus := applicationSet.Status.ApplicationStatus[idx]
- app, ok := appMap[appName]
- if !ok {
+
+ if app, ok := appMap[appName]; ok {
+ syncEnabled = appSyncEnabledForNextStep(&applicationSet, app, appStatus)
+ if !syncEnabled {
+ break
+ }
+ } else {
// application name not found in the list of applications managed by this ApplicationSet, maybe because it's being deleted
syncEnabled = false
break
}
- syncEnabled = appSyncEnabledForNextStep(&applicationSet, app, appStatus)
- if !syncEnabled {
- break
- }
}
}
@@ -1152,10 +1156,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]]++
+ totalCountMap[appStepMap[appStatus.Application]] += 1
if appStatus.Status == "Pending" || appStatus.Status == "Progressing" {
- updateCountMap[appStepMap[appStatus.Application]]++
+ updateCountMap[appStepMap[appStatus.Application]] += 1
}
}
@@ -1191,7 +1195,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]]++
+ updateCountMap[appStepMap[appStatus.Application]] += 1
}
appStatuses = append(appStatuses, appStatus)
@@ -1292,7 +1296,7 @@ func (r *ApplicationSetReconciler) migrateStatus(ctx context.Context, appset *ar
updatedAppset.DeepCopyInto(appset)
return nil
})
- if err != nil && !apierrors.IsNotFound(err) {
+ if err != nil && !apierr.IsNotFound(err) {
return fmt.Errorf("unable to set application set condition: %w", err)
}
}
@@ -1405,7 +1409,7 @@ func (r *ApplicationSetReconciler) syncValidApplications(logCtx *log.Entry, appl
pruneEnabled := false
// ensure that Applications generated with RollingSync do not have an automated sync policy, since the AppSet controller will handle triggering the sync operation instead
- if validApps[i].Spec.SyncPolicy != nil && validApps[i].Spec.SyncPolicy.IsAutomatedSyncEnabled() {
+ if validApps[i].Spec.SyncPolicy != nil && validApps[i].Spec.SyncPolicy.Automated != nil {
pruneEnabled = validApps[i].Spec.SyncPolicy.Automated.Prune
validApps[i].Spec.SyncPolicy.Automated = nil
}
@@ -1463,23 +1467,23 @@ func getApplicationOwnsHandler(enableProgressiveSyncs bool) predicate.Funcs {
// if we are the owner and there is a create event, we most likely created it and do not need to
// re-reconcile
if log.IsLevelEnabled(log.DebugLevel) {
- logFields := log.Fields{"app": ""}
+ var appName string
app, isApp := e.Object.(*argov1alpha1.Application)
if isApp {
- logFields = applog.GetAppLogFields(app)
+ appName = app.QualifiedName()
}
- log.WithFields(logFields).Debugln("received create event from owning an application")
+ log.WithField("app", appName).Debugln("received create event from owning an application")
}
return false
},
DeleteFunc: func(e event.DeleteEvent) bool {
if log.IsLevelEnabled(log.DebugLevel) {
- logFields := log.Fields{"app": ""}
+ var appName string
app, isApp := e.Object.(*argov1alpha1.Application)
if isApp {
- logFields = applog.GetAppLogFields(app)
+ appName = app.QualifiedName()
}
- log.WithFields(logFields).Debugln("received delete event from owning an application")
+ log.WithField("app", appName).Debugln("received delete event from owning an application")
}
return true
},
@@ -1488,7 +1492,7 @@ func getApplicationOwnsHandler(enableProgressiveSyncs bool) predicate.Funcs {
if !isApp {
return false
}
- logCtx := log.WithFields(applog.GetAppLogFields(appOld))
+ logCtx := log.WithField("app", appOld.QualifiedName())
logCtx.Debugln("received update event from owning an application")
appNew, isApp := e.ObjectNew.(*argov1alpha1.Application)
if !isApp {
@@ -1500,12 +1504,12 @@ func getApplicationOwnsHandler(enableProgressiveSyncs bool) predicate.Funcs {
},
GenericFunc: func(e event.GenericEvent) bool {
if log.IsLevelEnabled(log.DebugLevel) {
- logFields := log.Fields{}
+ var appName string
app, isApp := e.Object.(*argov1alpha1.Application)
if isApp {
- logFields = applog.GetAppLogFields(app)
+ appName = app.QualifiedName()
}
- log.WithFields(logFields).Debugln("received generic event from owning an application")
+ log.WithField("app", appName).Debugln("received generic event from owning an application")
}
return true
},
diff --git a/applicationset/controllers/applicationset_controller_test.go b/applicationset/controllers/applicationset_controller_test.go
index 544a881f46..e0974bd8ce 100644
--- a/applicationset/controllers/applicationset_controller_test.go
+++ b/applicationset/controllers/applicationset_controller_test.go
@@ -1,10 +1,12 @@
package controllers
import (
+ "context"
"encoding/json"
- "errors"
"fmt"
+ "reflect"
"strconv"
+ "strings"
"testing"
"time"
@@ -29,51 +31,18 @@ import (
"github.com/argoproj/gitops-engine/pkg/health"
"github.com/argoproj/gitops-engine/pkg/sync/common"
- "github.com/argoproj/argo-cd/v3/applicationset/generators"
- "github.com/argoproj/argo-cd/v3/applicationset/generators/mocks"
- appsetmetrics "github.com/argoproj/argo-cd/v3/applicationset/metrics"
- "github.com/argoproj/argo-cd/v3/applicationset/utils"
- argocommon "github.com/argoproj/argo-cd/v3/common"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- applog "github.com/argoproj/argo-cd/v3/util/app/log"
- "github.com/argoproj/argo-cd/v3/util/db"
- "github.com/argoproj/argo-cd/v3/util/settings"
+ "github.com/argoproj/argo-cd/v2/applicationset/generators"
+ "github.com/argoproj/argo-cd/v2/applicationset/generators/mocks"
+ "github.com/argoproj/argo-cd/v2/applicationset/utils"
+
+ appsetmetrics "github.com/argoproj/argo-cd/v2/applicationset/metrics"
+ argocommon "github.com/argoproj/argo-cd/v2/common"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+ dbmocks "github.com/argoproj/argo-cd/v2/util/db/mocks"
+
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application"
)
-// getDefaultTestClientSet creates a Clientset with the default argo objects
-// and objects specified in parameters
-func getDefaultTestClientSet(obj ...runtime.Object) *kubefake.Clientset {
- argoCDSecret := &corev1.Secret{
- ObjectMeta: metav1.ObjectMeta{
- Name: argocommon.ArgoCDSecretName,
- Namespace: "argocd",
- Labels: map[string]string{
- "app.kubernetes.io/part-of": "argocd",
- },
- },
- Data: map[string][]byte{
- "admin.password": nil,
- "server.secretkey": nil,
- },
- }
-
- emptyArgoCDConfigMap := &corev1.ConfigMap{
- ObjectMeta: metav1.ObjectMeta{
- Name: argocommon.ArgoCDConfigMapName,
- Namespace: "argocd",
- Labels: map[string]string{
- "app.kubernetes.io/part-of": "argocd",
- },
- },
- Data: map[string]string{},
- }
-
- objects := append(obj, emptyArgoCDConfigMap, argoCDSecret)
- kubeclientset := kubefake.NewClientset(objects...)
- return kubeclientset
-}
-
func TestCreateOrUpdateInCluster(t *testing.T) {
scheme := runtime.NewScheme()
err := v1alpha1.AddToScheme(scheme)
@@ -1088,7 +1057,7 @@ func TestCreateOrUpdateInCluster(t *testing.T) {
}
client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(initObjs...).WithIndex(&v1alpha1.Application{}, ".metadata.controller", appControllerIndexer).Build()
- metrics := appsetmetrics.NewFakeAppsetMetrics()
+ metrics := appsetmetrics.NewFakeAppsetMetrics(client)
r := ApplicationSetReconciler{
Client: client,
@@ -1097,12 +1066,12 @@ func TestCreateOrUpdateInCluster(t *testing.T) {
Metrics: metrics,
}
- err = r.createOrUpdateInCluster(t.Context(), log.NewEntry(log.StandardLogger()), c.appSet, c.desiredApps)
+ err = r.createOrUpdateInCluster(context.TODO(), log.NewEntry(log.StandardLogger()), c.appSet, c.desiredApps)
require.NoError(t, err)
for _, obj := range c.expected {
got := &v1alpha1.Application{}
- _ = client.Get(t.Context(), crtclient.ObjectKey{
+ _ = client.Get(context.Background(), crtclient.ObjectKey{
Namespace: obj.Namespace,
Name: obj.Name,
}, got)
@@ -1196,9 +1165,7 @@ func TestRemoveFinalizerOnInvalidDestination_FinalizerTypes(t *testing.T) {
objects := append([]runtime.Object{}, secret)
kubeclientset := kubefake.NewSimpleClientset(objects...)
- metrics := appsetmetrics.NewFakeAppsetMetrics()
-
- argodb := db.NewDB("argocd", settings.NewSettingsManager(t.Context(), kubeclientset, "argocd"), kubeclientset)
+ metrics := appsetmetrics.NewFakeAppsetMetrics(client)
r := ApplicationSetReconciler{
Client: client,
@@ -1206,20 +1173,22 @@ func TestRemoveFinalizerOnInvalidDestination_FinalizerTypes(t *testing.T) {
Recorder: record.NewFakeRecorder(10),
KubeClientset: kubeclientset,
Metrics: metrics,
- ArgoDB: argodb,
}
- clusterList, err := utils.ListClusters(t.Context(), kubeclientset, "namespace")
+ // settingsMgr := settings.NewSettingsManager(context.TODO(), kubeclientset, "namespace")
+ // argoDB := db.NewDB("namespace", settingsMgr, r.KubeClientset)
+ // clusterList, err := argoDB.ListClusters(context.Background())
+ clusterList, err := utils.ListClusters(context.Background(), kubeclientset, "namespace")
require.NoError(t, err)
- appLog := log.WithFields(applog.GetAppLogFields(&app)).WithField("appSet", "")
+ appLog := log.WithFields(log.Fields{"app": app.Name, "appSet": ""})
appInputParam := app.DeepCopy()
- err = r.removeFinalizerOnInvalidDestination(t.Context(), appSet, appInputParam, clusterList, appLog)
+ err = r.removeFinalizerOnInvalidDestination(context.Background(), appSet, appInputParam, clusterList, appLog)
require.NoError(t, err)
retrievedApp := v1alpha1.Application{}
- err = client.Get(t.Context(), crtclient.ObjectKeyFromObject(&app), &retrievedApp)
+ err = client.Get(context.Background(), crtclient.ObjectKeyFromObject(&app), &retrievedApp)
require.NoError(t, err)
// App on the cluster should have the expected finalizers
@@ -1336,7 +1305,7 @@ func TestRemoveFinalizerOnInvalidDestination_DestinationTypes(t *testing.T) {
secret := &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "my-secret",
- Namespace: "argocd",
+ Namespace: "namespace",
Labels: map[string]string{
argocommon.LabelKeySecretType: argocommon.LabelValueSecretTypeCluster,
},
@@ -1350,10 +1319,9 @@ func TestRemoveFinalizerOnInvalidDestination_DestinationTypes(t *testing.T) {
},
}
- kubeclientset := getDefaultTestClientSet(secret)
- metrics := appsetmetrics.NewFakeAppsetMetrics()
-
- argodb := db.NewDB("argocd", settings.NewSettingsManager(t.Context(), kubeclientset, "argocd"), kubeclientset)
+ objects := append([]runtime.Object{}, secret)
+ kubeclientset := kubefake.NewSimpleClientset(objects...)
+ metrics := appsetmetrics.NewFakeAppsetMetrics(client)
r := ApplicationSetReconciler{
Client: client,
@@ -1361,21 +1329,22 @@ func TestRemoveFinalizerOnInvalidDestination_DestinationTypes(t *testing.T) {
Recorder: record.NewFakeRecorder(10),
KubeClientset: kubeclientset,
Metrics: metrics,
- ArgoDB: argodb,
}
-
- clusterList, err := utils.ListClusters(t.Context(), kubeclientset, "argocd")
+ // settingsMgr := settings.NewSettingsManager(context.TODO(), kubeclientset, "argocd")
+ // argoDB := db.NewDB("argocd", settingsMgr, r.KubeClientset)
+ // clusterList, err := argoDB.ListClusters(context.Background())
+ clusterList, err := utils.ListClusters(context.Background(), kubeclientset, "namespace")
require.NoError(t, err)
- appLog := log.WithFields(applog.GetAppLogFields(&app)).WithField("appSet", "")
+ appLog := log.WithFields(log.Fields{"app": app.Name, "appSet": ""})
appInputParam := app.DeepCopy()
- err = r.removeFinalizerOnInvalidDestination(t.Context(), appSet, appInputParam, clusterList, appLog)
+ err = r.removeFinalizerOnInvalidDestination(context.Background(), appSet, appInputParam, clusterList, appLog)
require.NoError(t, err)
retrievedApp := v1alpha1.Application{}
- err = client.Get(t.Context(), crtclient.ObjectKeyFromObject(&app), &retrievedApp)
+ err = client.Get(context.Background(), crtclient.ObjectKeyFromObject(&app), &retrievedApp)
require.NoError(t, err)
finalizerRemoved := len(retrievedApp.Finalizers) == 0
@@ -1438,7 +1407,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()
+ metrics := appsetmetrics.NewFakeAppsetMetrics(client)
r := ApplicationSetReconciler{
Client: client,
@@ -1448,11 +1417,11 @@ func TestRemoveOwnerReferencesOnDeleteAppSet(t *testing.T) {
Metrics: metrics,
}
- err = r.removeOwnerReferencesOnDeleteAppSet(t.Context(), appSet)
+ err = r.removeOwnerReferencesOnDeleteAppSet(context.Background(), appSet)
require.NoError(t, err)
retrievedApp := v1alpha1.Application{}
- err = client.Get(t.Context(), crtclient.ObjectKeyFromObject(&app), &retrievedApp)
+ err = client.Get(context.Background(), crtclient.ObjectKeyFromObject(&app), &retrievedApp)
require.NoError(t, err)
ownerReferencesRemoved := len(retrievedApp.OwnerReferences) == 0
@@ -1637,7 +1606,7 @@ func TestCreateApplications(t *testing.T) {
}
client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(initObjs...).WithIndex(&v1alpha1.Application{}, ".metadata.controller", appControllerIndexer).Build()
- metrics := appsetmetrics.NewFakeAppsetMetrics()
+ metrics := appsetmetrics.NewFakeAppsetMetrics(client)
r := ApplicationSetReconciler{
Client: client,
@@ -1646,12 +1615,12 @@ func TestCreateApplications(t *testing.T) {
Metrics: metrics,
}
- err = r.createInCluster(t.Context(), log.NewEntry(log.StandardLogger()), c.appSet, c.apps)
+ err = r.createInCluster(context.TODO(), log.NewEntry(log.StandardLogger()), c.appSet, c.apps)
require.NoError(t, err)
for _, obj := range c.expected {
got := &v1alpha1.Application{}
- _ = client.Get(t.Context(), crtclient.ObjectKey{
+ _ = client.Get(context.Background(), crtclient.ObjectKey{
Namespace: obj.Namespace,
Name: obj.Name,
}, got)
@@ -1779,7 +1748,7 @@ func TestDeleteInCluster(t *testing.T) {
}
client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(initObjs...).WithIndex(&v1alpha1.Application{}, ".metadata.controller", appControllerIndexer).Build()
- metrics := appsetmetrics.NewFakeAppsetMetrics()
+ metrics := appsetmetrics.NewFakeAppsetMetrics(client)
r := ApplicationSetReconciler{
Client: client,
@@ -1789,13 +1758,13 @@ func TestDeleteInCluster(t *testing.T) {
Metrics: metrics,
}
- err = r.deleteInCluster(t.Context(), log.NewEntry(log.StandardLogger()), c.appSet, c.desiredApps)
+ err = r.deleteInCluster(context.TODO(), log.NewEntry(log.StandardLogger()), c.appSet, c.desiredApps)
require.NoError(t, err)
// For each of the expected objects, verify they exist on the cluster
for _, obj := range c.expected {
got := &v1alpha1.Application{}
- _ = client.Get(t.Context(), crtclient.ObjectKey{
+ _ = client.Get(context.Background(), crtclient.ObjectKey{
Namespace: obj.Namespace,
Name: obj.Name,
}, got)
@@ -1809,7 +1778,7 @@ func TestDeleteInCluster(t *testing.T) {
// Verify each of the unexpected objs cannot be found
for _, obj := range c.notExpected {
got := &v1alpha1.Application{}
- err := client.Get(t.Context(), crtclient.ObjectKey{
+ err := client.Get(context.Background(), crtclient.ObjectKey{
Namespace: obj.Namespace,
Name: obj.Name,
}, got)
@@ -1825,7 +1794,7 @@ func TestGetMinRequeueAfter(t *testing.T) {
require.NoError(t, err)
client := fake.NewClientBuilder().WithScheme(scheme).Build()
- metrics := appsetmetrics.NewFakeAppsetMetrics()
+ metrics := appsetmetrics.NewFakeAppsetMetrics(client)
generator := v1alpha1.ApplicationSetGenerator{
List: &v1alpha1.ListGenerator{},
@@ -1894,9 +1863,9 @@ 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]any{}, errors.New("Simulated error generating params that could be related to an external service/API call"))
+ Return([]map[string]interface{}{}, fmt.Errorf("Simulated error generating params that could be related to an external service/API call"))
- metrics := appsetmetrics.NewFakeAppsetMetrics()
+ metrics := appsetmetrics.NewFakeAppsetMetrics(client)
r := ApplicationSetReconciler{
Client: client,
@@ -1915,14 +1884,12 @@ func TestRequeueGeneratorFails(t *testing.T) {
},
}
- res, err := r.Reconcile(t.Context(), req)
+ res, err := r.Reconcile(context.Background(), req)
require.NoError(t, err)
assert.Equal(t, ReconcileRequeueOnValidationError, res.RequeueAfter)
}
func TestValidateGeneratedApplications(t *testing.T) {
- t.Parallel()
-
scheme := runtime.NewScheme()
err := v1alpha1.AddToScheme(scheme)
require.NoError(t, err)
@@ -1948,12 +1915,13 @@ func TestValidateGeneratedApplications(t *testing.T) {
}
client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(myProject).Build()
- metrics := appsetmetrics.NewFakeAppsetMetrics()
+ metrics := appsetmetrics.NewFakeAppsetMetrics(client)
// Test a subset of the validations that 'validateGeneratedApplications' performs
for _, cc := range []struct {
name string
apps []v1alpha1.Application
+ expectedErrors []string
validationErrors map[int]error
}{
{
@@ -1976,6 +1944,7 @@ func TestValidateGeneratedApplications(t *testing.T) {
},
},
},
+ expectedErrors: []string{},
validationErrors: map[int]error{},
},
{
@@ -1999,7 +1968,8 @@ func TestValidateGeneratedApplications(t *testing.T) {
},
},
},
- validationErrors: map[int]error{0: errors.New("application destination spec is invalid: application destination can't have both name and server defined: my-cluster my-server")},
+ expectedErrors: []string{"application destination can't have both name and server defined"},
+ validationErrors: map[int]error{0: fmt.Errorf("application destination spec is invalid: application destination can't have both name and server defined: my-cluster my-server")},
},
{
name: "project mismatch should return error",
@@ -2021,7 +1991,8 @@ func TestValidateGeneratedApplications(t *testing.T) {
},
},
},
- validationErrors: map[int]error{0: errors.New("application references project DOES-NOT-EXIST which does not exist")},
+ expectedErrors: []string{"application references project DOES-NOT-EXIST which does not exist"},
+ validationErrors: map[int]error{0: fmt.Errorf("application references project DOES-NOT-EXIST which does not exist")},
},
{
name: "valid app should return true",
@@ -2043,6 +2014,7 @@ func TestValidateGeneratedApplications(t *testing.T) {
},
},
},
+ expectedErrors: []string{},
validationErrors: map[int]error{},
},
{
@@ -2065,16 +2037,15 @@ func TestValidateGeneratedApplications(t *testing.T) {
},
},
},
- validationErrors: map[int]error{0: errors.New("application destination spec is invalid: there are no clusters with this name: nonexistent-cluster")},
+ expectedErrors: []string{"there are no clusters with this name: nonexistent-cluster"},
+ validationErrors: map[int]error{0: fmt.Errorf("application destination spec is invalid: unable to find destination server: there are no clusters with this name: nonexistent-cluster")},
},
} {
t.Run(cc.name, func(t *testing.T) {
- t.Parallel()
-
secret := &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "my-secret",
- Namespace: "argocd",
+ Namespace: "namespace",
Labels: map[string]string{
argocommon.LabelKeySecretType: argocommon.LabelValueSecretTypeCluster,
},
@@ -2086,24 +2057,51 @@ func TestValidateGeneratedApplications(t *testing.T) {
},
}
- kubeclientset := getDefaultTestClientSet(secret)
-
- argodb := db.NewDB("argocd", settings.NewSettingsManager(t.Context(), kubeclientset, "argocd"), kubeclientset)
+ objects := append([]runtime.Object{}, secret)
+ kubeclientset := kubefake.NewSimpleClientset(objects...)
r := ApplicationSetReconciler{
Client: client,
Scheme: scheme,
Recorder: record.NewFakeRecorder(1),
Generators: map[string]generators.Generator{},
- ArgoDB: argodb,
+ ArgoDB: &dbmocks.ArgoDB{},
ArgoCDNamespace: "namespace",
KubeClientset: kubeclientset,
Metrics: metrics,
}
appSetInfo := v1alpha1.ApplicationSet{}
- validationErrors, _ := r.validateGeneratedApplications(t.Context(), cc.apps, appSetInfo)
- assert.Equal(t, cc.validationErrors, validationErrors)
+
+ validationErrors, _ := r.validateGeneratedApplications(context.TODO(), cc.apps, appSetInfo)
+ var errorMessages []string
+ for _, v := range validationErrors {
+ errorMessages = append(errorMessages, v.Error())
+ }
+
+ if len(errorMessages) == 0 {
+ assert.Empty(t, cc.expectedErrors, "Expected errors but none were seen")
+ } else {
+ // An error was returned: it should be expected
+ matched := false
+ for _, expectedErr := range cc.expectedErrors {
+ foundMatch := strings.Contains(strings.Join(errorMessages, ";"), expectedErr)
+ assert.True(t, foundMatch, "Unble to locate expected error: %s", cc.expectedErrors)
+ matched = matched || foundMatch
+ }
+ assert.True(t, matched, "An unexpected error occurrred: %v", err)
+ // validation message was returned: it should be expected
+ matched = false
+ foundMatch := reflect.DeepEqual(validationErrors, cc.validationErrors)
+ var message string
+ for _, v := range validationErrors {
+ message = v.Error()
+ break
+ }
+ assert.True(t, foundMatch, "Unble to locate validation message: %s", message)
+ matched = matched || foundMatch
+ assert.True(t, matched, "An unexpected error occurrred: %v", err)
+ }
})
}
}
@@ -2148,12 +2146,10 @@ func TestReconcilerValidationProjectErrorBehaviour(t *testing.T) {
},
}
- kubeclientset := getDefaultTestClientSet()
+ kubeclientset := kubefake.NewSimpleClientset()
client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(&appSet, &project).WithStatusSubresource(&appSet).WithIndex(&v1alpha1.Application{}, ".metadata.controller", appControllerIndexer).Build()
- metrics := appsetmetrics.NewFakeAppsetMetrics()
-
- argodb := db.NewDB("argocd", settings.NewSettingsManager(t.Context(), kubeclientset, "argocd"), kubeclientset)
+ metrics := appsetmetrics.NewFakeAppsetMetrics(client)
r := ApplicationSetReconciler{
Client: client,
@@ -2163,7 +2159,7 @@ func TestReconcilerValidationProjectErrorBehaviour(t *testing.T) {
Generators: map[string]generators.Generator{
"List": generators.NewListGenerator(),
},
- ArgoDB: argodb,
+ ArgoDB: &dbmocks.ArgoDB{},
KubeClientset: kubeclientset,
Policy: v1alpha1.ApplicationsSyncPolicySync,
ArgoCDNamespace: "argocd",
@@ -2178,19 +2174,19 @@ func TestReconcilerValidationProjectErrorBehaviour(t *testing.T) {
}
// Verify that on validation error, no error is returned, but the object is requeued
- res, err := r.Reconcile(t.Context(), req)
+ res, err := r.Reconcile(context.Background(), req)
require.NoError(t, err)
assert.Equal(t, ReconcileRequeueOnValidationError, res.RequeueAfter)
var app v1alpha1.Application
// make sure good app got created
- err = r.Get(t.Context(), crtclient.ObjectKey{Namespace: "argocd", Name: "good-project"}, &app)
+ err = r.Client.Get(context.TODO(), crtclient.ObjectKey{Namespace: "argocd", Name: "good-project"}, &app)
require.NoError(t, err)
assert.Equal(t, "good-project", app.Name)
// make sure bad app was not created
- err = r.Get(t.Context(), crtclient.ObjectKey{Namespace: "argocd", Name: "bad-project"}, &app)
+ err = r.Client.Get(context.TODO(), crtclient.ObjectKey{Namespace: "argocd", Name: "bad-project"}, &app)
require.Error(t, err)
}
@@ -2350,9 +2346,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()
-
- argodb := db.NewDB("argocd", settings.NewSettingsManager(t.Context(), kubeclientset, "argocd"), kubeclientset)
+ metrics := appsetmetrics.NewFakeAppsetMetrics(client)
r := ApplicationSetReconciler{
Client: client,
@@ -2362,13 +2356,13 @@ func TestSetApplicationSetStatusCondition(t *testing.T) {
Generators: map[string]generators.Generator{
"List": generators.NewListGenerator(),
},
- ArgoDB: argodb,
+ ArgoDB: &dbmocks.ArgoDB{},
KubeClientset: kubeclientset,
Metrics: metrics,
}
for _, condition := range testCase.conditions {
- err = r.setApplicationSetStatusCondition(t.Context(), &testCase.appset, condition, true)
+ err = r.setApplicationSetStatusCondition(context.TODO(), &testCase.appset, condition, true)
require.NoError(t, err)
}
@@ -2435,12 +2429,11 @@ func applicationsUpdateSyncPolicyTest(t *testing.T, applicationsSyncPolicy v1alp
},
}
- kubeclientset := getDefaultTestClientSet(secret)
+ objects := append([]runtime.Object{}, secret)
+ kubeclientset := kubefake.NewSimpleClientset(objects...)
client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(&appSet, &defaultProject).WithStatusSubresource(&appSet).WithIndex(&v1alpha1.Application{}, ".metadata.controller", appControllerIndexer).Build()
- metrics := appsetmetrics.NewFakeAppsetMetrics()
-
- argodb := db.NewDB("argocd", settings.NewSettingsManager(t.Context(), kubeclientset, "argocd"), kubeclientset)
+ metrics := appsetmetrics.NewFakeAppsetMetrics(client)
r := ApplicationSetReconciler{
Client: client,
@@ -2450,7 +2443,7 @@ func applicationsUpdateSyncPolicyTest(t *testing.T, applicationsSyncPolicy v1alp
Generators: map[string]generators.Generator{
"List": generators.NewListGenerator(),
},
- ArgoDB: argodb,
+ ArgoDB: &dbmocks.ArgoDB{},
ArgoCDNamespace: "argocd",
KubeClientset: kubeclientset,
Policy: v1alpha1.ApplicationsSyncPolicySync,
@@ -2466,20 +2459,20 @@ func applicationsUpdateSyncPolicyTest(t *testing.T, applicationsSyncPolicy v1alp
}
// Verify that on validation error, no error is returned, but the object is requeued
- resCreate, err := r.Reconcile(t.Context(), req)
- require.NoErrorf(t, err, "Reconcile failed with error: %v", err)
+ resCreate, err := r.Reconcile(context.Background(), req)
+ require.NoError(t, err)
assert.Equal(t, time.Duration(0), resCreate.RequeueAfter)
var app v1alpha1.Application
// make sure good app got created
- err = r.Get(t.Context(), crtclient.ObjectKey{Namespace: "argocd", Name: "good-cluster"}, &app)
+ err = r.Client.Get(context.TODO(), crtclient.ObjectKey{Namespace: "argocd", Name: "good-cluster"}, &app)
require.NoError(t, err)
assert.Equal(t, "good-cluster", app.Name)
// Update resource
var retrievedApplicationSet v1alpha1.ApplicationSet
- err = r.Get(t.Context(), crtclient.ObjectKey{Namespace: "argocd", Name: "name"}, &retrievedApplicationSet)
+ err = r.Client.Get(context.TODO(), crtclient.ObjectKey{Namespace: "argocd", Name: "name"}, &retrievedApplicationSet)
require.NoError(t, err)
retrievedApplicationSet.Spec.Template.Annotations = map[string]string{"annotation-key": "annotation-value"}
@@ -2489,13 +2482,13 @@ func applicationsUpdateSyncPolicyTest(t *testing.T, applicationsSyncPolicy v1alp
Values: "global.test: test",
}
- err = r.Update(t.Context(), &retrievedApplicationSet)
+ err = r.Client.Update(context.TODO(), &retrievedApplicationSet)
require.NoError(t, err)
- resUpdate, err := r.Reconcile(t.Context(), req)
+ resUpdate, err := r.Reconcile(context.Background(), req)
require.NoError(t, err)
- err = r.Get(t.Context(), crtclient.ObjectKey{Namespace: "argocd", Name: "good-cluster"}, &app)
+ err = r.Client.Get(context.TODO(), crtclient.ObjectKey{Namespace: "argocd", Name: "good-cluster"}, &app)
require.NoError(t, err)
assert.Equal(t, time.Duration(0), resUpdate.RequeueAfter)
assert.Equal(t, "good-cluster", app.Name)
@@ -2509,7 +2502,7 @@ func TestUpdateNotPerformedWithSyncPolicyCreateOnly(t *testing.T) {
app := applicationsUpdateSyncPolicyTest(t, applicationsSyncPolicy, 1, true)
assert.Nil(t, app.Spec.Source.Helm)
- assert.Nil(t, app.Annotations)
+ assert.Nil(t, app.ObjectMeta.Annotations)
}
func TestUpdateNotPerformedWithSyncPolicyCreateDelete(t *testing.T) {
@@ -2518,7 +2511,7 @@ func TestUpdateNotPerformedWithSyncPolicyCreateDelete(t *testing.T) {
app := applicationsUpdateSyncPolicyTest(t, applicationsSyncPolicy, 1, true)
assert.Nil(t, app.Spec.Source.Helm)
- assert.Nil(t, app.Annotations)
+ assert.Nil(t, app.ObjectMeta.Annotations)
}
func TestUpdatePerformedWithSyncPolicyCreateUpdate(t *testing.T) {
@@ -2527,8 +2520,8 @@ func TestUpdatePerformedWithSyncPolicyCreateUpdate(t *testing.T) {
app := applicationsUpdateSyncPolicyTest(t, applicationsSyncPolicy, 2, true)
assert.Equal(t, "global.test: test", app.Spec.Source.Helm.Values)
- assert.Equal(t, map[string]string{"annotation-key": "annotation-value"}, app.Annotations)
- assert.Equal(t, map[string]string{"label-key": "label-value"}, app.Labels)
+ assert.Equal(t, map[string]string{"annotation-key": "annotation-value"}, app.ObjectMeta.Annotations)
+ assert.Equal(t, map[string]string{"label-key": "label-value"}, app.ObjectMeta.Labels)
}
func TestUpdatePerformedWithSyncPolicySync(t *testing.T) {
@@ -2537,8 +2530,8 @@ func TestUpdatePerformedWithSyncPolicySync(t *testing.T) {
app := applicationsUpdateSyncPolicyTest(t, applicationsSyncPolicy, 2, true)
assert.Equal(t, "global.test: test", app.Spec.Source.Helm.Values)
- assert.Equal(t, map[string]string{"annotation-key": "annotation-value"}, app.Annotations)
- assert.Equal(t, map[string]string{"label-key": "label-value"}, app.Labels)
+ assert.Equal(t, map[string]string{"annotation-key": "annotation-value"}, app.ObjectMeta.Annotations)
+ assert.Equal(t, map[string]string{"label-key": "label-value"}, app.ObjectMeta.Labels)
}
func TestUpdatePerformedWithSyncPolicyCreateOnlyAndAllowPolicyOverrideFalse(t *testing.T) {
@@ -2547,8 +2540,8 @@ func TestUpdatePerformedWithSyncPolicyCreateOnlyAndAllowPolicyOverrideFalse(t *t
app := applicationsUpdateSyncPolicyTest(t, applicationsSyncPolicy, 2, false)
assert.Equal(t, "global.test: test", app.Spec.Source.Helm.Values)
- assert.Equal(t, map[string]string{"annotation-key": "annotation-value"}, app.Annotations)
- assert.Equal(t, map[string]string{"label-key": "label-value"}, app.Labels)
+ assert.Equal(t, map[string]string{"annotation-key": "annotation-value"}, app.ObjectMeta.Annotations)
+ assert.Equal(t, map[string]string{"label-key": "label-value"}, app.ObjectMeta.Labels)
}
func applicationsDeleteSyncPolicyTest(t *testing.T, applicationsSyncPolicy v1alpha1.ApplicationsSyncPolicy, recordBuffer int, allowPolicyOverride bool) v1alpha1.ApplicationList {
@@ -2610,12 +2603,11 @@ func applicationsDeleteSyncPolicyTest(t *testing.T, applicationsSyncPolicy v1alp
},
}
- kubeclientset := getDefaultTestClientSet(secret)
+ objects := append([]runtime.Object{}, secret)
+ kubeclientset := kubefake.NewSimpleClientset(objects...)
client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(&appSet, &defaultProject).WithStatusSubresource(&appSet).WithIndex(&v1alpha1.Application{}, ".metadata.controller", appControllerIndexer).Build()
- metrics := appsetmetrics.NewFakeAppsetMetrics()
-
- argodb := db.NewDB("argocd", settings.NewSettingsManager(t.Context(), kubeclientset, "argocd"), kubeclientset)
+ metrics := appsetmetrics.NewFakeAppsetMetrics(client)
r := ApplicationSetReconciler{
Client: client,
@@ -2625,7 +2617,7 @@ func applicationsDeleteSyncPolicyTest(t *testing.T, applicationsSyncPolicy v1alp
Generators: map[string]generators.Generator{
"List": generators.NewListGenerator(),
},
- ArgoDB: argodb,
+ ArgoDB: &dbmocks.ArgoDB{},
ArgoCDNamespace: "argocd",
KubeClientset: kubeclientset,
Policy: v1alpha1.ApplicationsSyncPolicySync,
@@ -2641,20 +2633,20 @@ func applicationsDeleteSyncPolicyTest(t *testing.T, applicationsSyncPolicy v1alp
}
// Verify that on validation error, no error is returned, but the object is requeued
- resCreate, err := r.Reconcile(t.Context(), req)
+ resCreate, err := r.Reconcile(context.Background(), req)
require.NoError(t, err)
assert.Equal(t, time.Duration(0), resCreate.RequeueAfter)
var app v1alpha1.Application
// make sure good app got created
- err = r.Get(t.Context(), crtclient.ObjectKey{Namespace: "argocd", Name: "good-cluster"}, &app)
+ err = r.Client.Get(context.TODO(), crtclient.ObjectKey{Namespace: "argocd", Name: "good-cluster"}, &app)
require.NoError(t, err)
assert.Equal(t, "good-cluster", app.Name)
// Update resource
var retrievedApplicationSet v1alpha1.ApplicationSet
- err = r.Get(t.Context(), crtclient.ObjectKey{Namespace: "argocd", Name: "name"}, &retrievedApplicationSet)
+ err = r.Client.Get(context.TODO(), crtclient.ObjectKey{Namespace: "argocd", Name: "name"}, &retrievedApplicationSet)
require.NoError(t, err)
retrievedApplicationSet.Spec.Generators = []v1alpha1.ApplicationSetGenerator{
{
@@ -2664,15 +2656,15 @@ func applicationsDeleteSyncPolicyTest(t *testing.T, applicationsSyncPolicy v1alp
},
}
- err = r.Update(t.Context(), &retrievedApplicationSet)
+ err = r.Client.Update(context.TODO(), &retrievedApplicationSet)
require.NoError(t, err)
- resUpdate, err := r.Reconcile(t.Context(), req)
+ resUpdate, err := r.Reconcile(context.Background(), req)
require.NoError(t, err)
var apps v1alpha1.ApplicationList
- err = r.List(t.Context(), &apps)
+ err = r.Client.List(context.TODO(), &apps)
require.NoError(t, err)
assert.Equal(t, time.Duration(0), resUpdate.RequeueAfter)
@@ -2729,7 +2721,7 @@ func TestPolicies(t *testing.T) {
Spec: v1alpha1.AppProjectSpec{SourceRepos: []string{"*"}, Destinations: []v1alpha1.ApplicationDestination{{Namespace: "*", Server: "https://kubernetes.default.svc"}}},
}
- kubeclientset := getDefaultTestClientSet()
+ kubeclientset := kubefake.NewSimpleClientset()
for _, c := range []struct {
name string
@@ -2802,9 +2794,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()
-
- argodb := db.NewDB("argocd", settings.NewSettingsManager(t.Context(), kubeclientset, "argocd"), kubeclientset)
+ metrics := appsetmetrics.NewFakeAppsetMetrics(client)
r := ApplicationSetReconciler{
Client: client,
@@ -2814,7 +2804,7 @@ func TestPolicies(t *testing.T) {
Generators: map[string]generators.Generator{
"List": generators.NewListGenerator(),
},
- ArgoDB: argodb,
+ ArgoDB: &dbmocks.ArgoDB{},
ArgoCDNamespace: "argocd",
KubeClientset: kubeclientset,
Policy: policy,
@@ -2829,25 +2819,25 @@ func TestPolicies(t *testing.T) {
}
// Check if Application is created
- res, err := r.Reconcile(t.Context(), req)
+ res, err := r.Reconcile(context.Background(), req)
require.NoError(t, err)
assert.Equal(t, time.Duration(0), res.RequeueAfter)
var app v1alpha1.Application
- err = r.Get(t.Context(), crtclient.ObjectKey{Namespace: "argocd", Name: "my-app"}, &app)
+ err = r.Client.Get(context.TODO(), crtclient.ObjectKey{Namespace: "argocd", Name: "my-app"}, &app)
require.NoError(t, err)
assert.Equal(t, "value", app.Annotations["key"])
// Check if Application is updated
app.Annotations["key"] = "edited"
- err = r.Update(t.Context(), &app)
+ err = r.Client.Update(context.TODO(), &app)
require.NoError(t, err)
- res, err = r.Reconcile(t.Context(), req)
+ res, err = r.Reconcile(context.Background(), req)
require.NoError(t, err)
assert.Equal(t, time.Duration(0), res.RequeueAfter)
- err = r.Get(t.Context(), crtclient.ObjectKey{Namespace: "argocd", Name: "my-app"}, &app)
+ err = r.Client.Get(context.TODO(), crtclient.ObjectKey{Namespace: "argocd", Name: "my-app"}, &app)
require.NoError(t, err)
if c.allowedUpdate {
@@ -2857,21 +2847,21 @@ func TestPolicies(t *testing.T) {
}
// Check if Application is deleted
- err = r.Get(t.Context(), crtclient.ObjectKey{Namespace: "argocd", Name: "name"}, &appSet)
+ err = r.Client.Get(context.TODO(), crtclient.ObjectKey{Namespace: "argocd", Name: "name"}, &appSet)
require.NoError(t, err)
appSet.Spec.Generators[0] = v1alpha1.ApplicationSetGenerator{
List: &v1alpha1.ListGenerator{
Elements: []apiextensionsv1.JSON{},
},
}
- err = r.Update(t.Context(), &appSet)
+ err = r.Client.Update(context.TODO(), &appSet)
require.NoError(t, err)
- res, err = r.Reconcile(t.Context(), req)
+ res, err = r.Reconcile(context.Background(), req)
require.NoError(t, err)
assert.Equal(t, time.Duration(0), res.RequeueAfter)
- err = r.Get(t.Context(), crtclient.ObjectKey{Namespace: "argocd", Name: "my-app"}, &app)
+ err = r.Client.Get(context.TODO(), crtclient.ObjectKey{Namespace: "argocd", Name: "my-app"}, &app)
require.NoError(t, err)
if c.allowedDelete {
assert.NotNil(t, app.DeletionTimestamp)
@@ -2961,9 +2951,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()
-
- argodb := db.NewDB("argocd", settings.NewSettingsManager(t.Context(), kubeclientset, "argocd"), kubeclientset)
+ metrics := appsetmetrics.NewFakeAppsetMetrics(client)
r := ApplicationSetReconciler{
Client: client,
@@ -2973,12 +2961,12 @@ func TestSetApplicationSetApplicationStatus(t *testing.T) {
Generators: map[string]generators.Generator{
"List": generators.NewListGenerator(),
},
- ArgoDB: argodb,
+ ArgoDB: &dbmocks.ArgoDB{},
KubeClientset: kubeclientset,
Metrics: metrics,
}
- err = r.setAppSetApplicationStatus(t.Context(), log.NewEntry(log.StandardLogger()), &cc.appSet, cc.appStatuses)
+ err = r.setAppSetApplicationStatus(context.TODO(), log.NewEntry(log.StandardLogger()), &cc.appSet, cc.appStatuses)
require.NoError(t, err)
assert.Equal(t, cc.expectedAppStatuses, cc.appSet.Status.ApplicationStatus)
@@ -2992,7 +2980,7 @@ func TestBuildAppDependencyList(t *testing.T) {
require.NoError(t, err)
client := fake.NewClientBuilder().WithScheme(scheme).Build()
- metrics := appsetmetrics.NewFakeAppsetMetrics()
+ metrics := appsetmetrics.NewFakeAppsetMetrics(client)
for _, cc := range []struct {
name string
@@ -3723,14 +3711,12 @@ func TestBuildAppDependencyList(t *testing.T) {
t.Run(cc.name, func(t *testing.T) {
kubeclientset := kubefake.NewSimpleClientset([]runtime.Object{}...)
- argodb := db.NewDB("argocd", settings.NewSettingsManager(t.Context(), kubeclientset, "argocd"), kubeclientset)
-
r := ApplicationSetReconciler{
Client: client,
Scheme: scheme,
Recorder: record.NewFakeRecorder(1),
Generators: map[string]generators.Generator{},
- ArgoDB: argodb,
+ ArgoDB: &dbmocks.ArgoDB{},
KubeClientset: kubeclientset,
Metrics: metrics,
}
@@ -3748,7 +3734,7 @@ func TestBuildAppSyncMap(t *testing.T) {
require.NoError(t, err)
client := fake.NewClientBuilder().WithScheme(scheme).Build()
- metrics := appsetmetrics.NewFakeAppsetMetrics()
+ metrics := appsetmetrics.NewFakeAppsetMetrics(client)
for _, cc := range []struct {
name string
@@ -3888,7 +3874,7 @@ func TestBuildAppSyncMap(t *testing.T) {
Name: "app1",
},
Status: v1alpha1.ApplicationStatus{
- Health: v1alpha1.AppHealthStatus{
+ Health: v1alpha1.HealthStatus{
Status: health.HealthStatusHealthy,
},
OperationState: &v1alpha1.OperationState{
@@ -3904,7 +3890,7 @@ func TestBuildAppSyncMap(t *testing.T) {
Name: "app2",
},
Status: v1alpha1.ApplicationStatus{
- Health: v1alpha1.AppHealthStatus{
+ Health: v1alpha1.HealthStatus{
Status: health.HealthStatusHealthy,
},
OperationState: &v1alpha1.OperationState{
@@ -3966,7 +3952,7 @@ func TestBuildAppSyncMap(t *testing.T) {
Name: "app1",
},
Status: v1alpha1.ApplicationStatus{
- Health: v1alpha1.AppHealthStatus{
+ Health: v1alpha1.HealthStatus{
Status: health.HealthStatusHealthy,
},
OperationState: &v1alpha1.OperationState{
@@ -3982,7 +3968,7 @@ func TestBuildAppSyncMap(t *testing.T) {
Name: "app2",
},
Status: v1alpha1.ApplicationStatus{
- Health: v1alpha1.AppHealthStatus{
+ Health: v1alpha1.HealthStatus{
Status: health.HealthStatusHealthy,
},
OperationState: &v1alpha1.OperationState{
@@ -4044,7 +4030,7 @@ func TestBuildAppSyncMap(t *testing.T) {
Name: "app1",
},
Status: v1alpha1.ApplicationStatus{
- Health: v1alpha1.AppHealthStatus{
+ Health: v1alpha1.HealthStatus{
Status: health.HealthStatusHealthy,
},
OperationState: &v1alpha1.OperationState{
@@ -4060,7 +4046,7 @@ func TestBuildAppSyncMap(t *testing.T) {
Name: "app2",
},
Status: v1alpha1.ApplicationStatus{
- Health: v1alpha1.AppHealthStatus{
+ Health: v1alpha1.HealthStatus{
Status: health.HealthStatusHealthy,
},
OperationState: &v1alpha1.OperationState{
@@ -4122,7 +4108,7 @@ func TestBuildAppSyncMap(t *testing.T) {
Name: "app1",
},
Status: v1alpha1.ApplicationStatus{
- Health: v1alpha1.AppHealthStatus{
+ Health: v1alpha1.HealthStatus{
Status: health.HealthStatusDegraded,
},
OperationState: &v1alpha1.OperationState{
@@ -4138,7 +4124,7 @@ func TestBuildAppSyncMap(t *testing.T) {
Name: "app2",
},
Status: v1alpha1.ApplicationStatus{
- Health: v1alpha1.AppHealthStatus{
+ Health: v1alpha1.HealthStatus{
Status: health.HealthStatusDegraded,
},
OperationState: &v1alpha1.OperationState{
@@ -4204,7 +4190,7 @@ func TestBuildAppSyncMap(t *testing.T) {
Name: "app1",
},
Status: v1alpha1.ApplicationStatus{
- Health: v1alpha1.AppHealthStatus{
+ Health: v1alpha1.HealthStatus{
Status: health.HealthStatusHealthy,
},
OperationState: &v1alpha1.OperationState{
@@ -4220,7 +4206,7 @@ func TestBuildAppSyncMap(t *testing.T) {
Name: "app2",
},
Status: v1alpha1.ApplicationStatus{
- Health: v1alpha1.AppHealthStatus{
+ Health: v1alpha1.HealthStatus{
Status: health.HealthStatusHealthy,
},
OperationState: &v1alpha1.OperationState{
@@ -4294,7 +4280,7 @@ func TestBuildAppSyncMap(t *testing.T) {
Name: "app1",
},
Status: v1alpha1.ApplicationStatus{
- Health: v1alpha1.AppHealthStatus{
+ Health: v1alpha1.HealthStatus{
Status: health.HealthStatusHealthy,
},
OperationState: &v1alpha1.OperationState{
@@ -4310,7 +4296,7 @@ func TestBuildAppSyncMap(t *testing.T) {
Name: "app2",
},
Status: v1alpha1.ApplicationStatus{
- Health: v1alpha1.AppHealthStatus{
+ Health: v1alpha1.HealthStatus{
Status: health.HealthStatusHealthy,
},
OperationState: &v1alpha1.OperationState{
@@ -4326,7 +4312,7 @@ func TestBuildAppSyncMap(t *testing.T) {
Name: "app3",
},
Status: v1alpha1.ApplicationStatus{
- Health: v1alpha1.AppHealthStatus{
+ Health: v1alpha1.HealthStatus{
Status: health.HealthStatusHealthy,
},
OperationState: &v1alpha1.OperationState{
@@ -4342,7 +4328,7 @@ func TestBuildAppSyncMap(t *testing.T) {
Name: "app5",
},
Status: v1alpha1.ApplicationStatus{
- Health: v1alpha1.AppHealthStatus{
+ Health: v1alpha1.HealthStatus{
Status: health.HealthStatusHealthy,
},
OperationState: &v1alpha1.OperationState{
@@ -4358,7 +4344,7 @@ func TestBuildAppSyncMap(t *testing.T) {
Name: "app6",
},
Status: v1alpha1.ApplicationStatus{
- Health: v1alpha1.AppHealthStatus{
+ Health: v1alpha1.HealthStatus{
Status: health.HealthStatusDegraded,
},
OperationState: &v1alpha1.OperationState{
@@ -4391,14 +4377,12 @@ func TestBuildAppSyncMap(t *testing.T) {
t.Run(cc.name, func(t *testing.T) {
kubeclientset := kubefake.NewSimpleClientset([]runtime.Object{}...)
- argodb := db.NewDB("argocd", settings.NewSettingsManager(t.Context(), kubeclientset, "argocd"), kubeclientset)
-
r := ApplicationSetReconciler{
Client: client,
Scheme: scheme,
Recorder: record.NewFakeRecorder(1),
Generators: map[string]generators.Generator{},
- ArgoDB: argodb,
+ ArgoDB: &dbmocks.ArgoDB{},
KubeClientset: kubeclientset,
Metrics: metrics,
}
@@ -4476,7 +4460,7 @@ func TestUpdateApplicationSetApplicationStatus(t *testing.T) {
Name: "app1",
},
Status: v1alpha1.ApplicationStatus{
- Health: v1alpha1.AppHealthStatus{
+ Health: v1alpha1.HealthStatus{
Status: health.HealthStatusHealthy,
},
OperationState: &v1alpha1.OperationState{
@@ -4531,7 +4515,7 @@ func TestUpdateApplicationSetApplicationStatus(t *testing.T) {
Name: "app1",
},
Status: v1alpha1.ApplicationStatus{
- Health: v1alpha1.AppHealthStatus{
+ Health: v1alpha1.HealthStatus{
Status: health.HealthStatusHealthy,
},
OperationState: &v1alpha1.OperationState{
@@ -4595,7 +4579,7 @@ func TestUpdateApplicationSetApplicationStatus(t *testing.T) {
Name: "app1",
},
Status: v1alpha1.ApplicationStatus{
- Health: v1alpha1.AppHealthStatus{
+ Health: v1alpha1.HealthStatus{
Status: health.HealthStatusHealthy,
},
OperationState: &v1alpha1.OperationState{
@@ -4746,7 +4730,7 @@ func TestUpdateApplicationSetApplicationStatus(t *testing.T) {
Name: "app1",
},
Status: v1alpha1.ApplicationStatus{
- Health: v1alpha1.AppHealthStatus{
+ Health: v1alpha1.HealthStatus{
Status: health.HealthStatusProgressing,
},
Sync: v1alpha1.SyncStatus{
@@ -4808,7 +4792,7 @@ func TestUpdateApplicationSetApplicationStatus(t *testing.T) {
Name: "app1",
},
Status: v1alpha1.ApplicationStatus{
- Health: v1alpha1.AppHealthStatus{
+ Health: v1alpha1.HealthStatus{
Status: health.HealthStatusHealthy,
},
OperationState: &v1alpha1.OperationState{
@@ -4874,7 +4858,7 @@ func TestUpdateApplicationSetApplicationStatus(t *testing.T) {
Name: "app1",
},
Status: v1alpha1.ApplicationStatus{
- Health: v1alpha1.AppHealthStatus{
+ Health: v1alpha1.HealthStatus{
Status: health.HealthStatusHealthy,
},
OperationState: &v1alpha1.OperationState{
@@ -4940,7 +4924,7 @@ func TestUpdateApplicationSetApplicationStatus(t *testing.T) {
Name: "app1",
},
Status: v1alpha1.ApplicationStatus{
- Health: v1alpha1.AppHealthStatus{
+ Health: v1alpha1.HealthStatus{
Status: health.HealthStatusHealthy,
},
OperationState: &v1alpha1.OperationState{
@@ -4995,7 +4979,7 @@ func TestUpdateApplicationSetApplicationStatus(t *testing.T) {
Name: "app1",
},
Status: v1alpha1.ApplicationStatus{
- Health: v1alpha1.AppHealthStatus{
+ Health: v1alpha1.HealthStatus{
Status: health.HealthStatusHealthy,
},
OperationState: &v1alpha1.OperationState{
@@ -5068,7 +5052,7 @@ func TestUpdateApplicationSetApplicationStatus(t *testing.T) {
Name: "app1",
},
Status: v1alpha1.ApplicationStatus{
- Health: v1alpha1.AppHealthStatus{
+ Health: v1alpha1.HealthStatus{
Status: health.HealthStatusDegraded,
},
OperationState: &v1alpha1.OperationState{
@@ -5149,7 +5133,7 @@ func TestUpdateApplicationSetApplicationStatus(t *testing.T) {
Name: "app1",
},
Status: v1alpha1.ApplicationStatus{
- Health: v1alpha1.AppHealthStatus{
+ Health: v1alpha1.HealthStatus{
Status: health.HealthStatusDegraded,
},
OperationState: &v1alpha1.OperationState{
@@ -5234,7 +5218,7 @@ func TestUpdateApplicationSetApplicationStatus(t *testing.T) {
Name: "app1",
},
Status: v1alpha1.ApplicationStatus{
- Health: v1alpha1.AppHealthStatus{
+ Health: v1alpha1.HealthStatus{
Status: health.HealthStatusHealthy,
},
OperationState: &v1alpha1.OperationState{
@@ -5300,7 +5284,7 @@ func TestUpdateApplicationSetApplicationStatus(t *testing.T) {
Name: "app1",
},
Status: v1alpha1.ApplicationStatus{
- Health: v1alpha1.AppHealthStatus{
+ Health: v1alpha1.HealthStatus{
Status: health.HealthStatusHealthy,
},
OperationState: &v1alpha1.OperationState{
@@ -5334,21 +5318,19 @@ 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()
-
- argodb := db.NewDB("argocd", settings.NewSettingsManager(t.Context(), kubeclientset, "argocd"), kubeclientset)
+ metrics := appsetmetrics.NewFakeAppsetMetrics(client)
r := ApplicationSetReconciler{
Client: client,
Scheme: scheme,
Recorder: record.NewFakeRecorder(1),
Generators: map[string]generators.Generator{},
- ArgoDB: argodb,
+ ArgoDB: &dbmocks.ArgoDB{},
KubeClientset: kubeclientset,
Metrics: metrics,
}
- appStatuses, err := r.updateApplicationSetApplicationStatus(t.Context(), log.NewEntry(log.StandardLogger()), &cc.appSet, cc.apps, cc.appStepMap)
+ appStatuses, err := r.updateApplicationSetApplicationStatus(context.TODO(), log.NewEntry(log.StandardLogger()), &cc.appSet, cc.apps, cc.appStepMap)
// opt out of testing the LastTransitionTime is accurate
for i := range appStatuses {
@@ -6084,21 +6066,19 @@ 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()
-
- argodb := db.NewDB("argocd", settings.NewSettingsManager(t.Context(), kubeclientset, "argocd"), kubeclientset)
+ metrics := appsetmetrics.NewFakeAppsetMetrics(client)
r := ApplicationSetReconciler{
Client: client,
Scheme: scheme,
Recorder: record.NewFakeRecorder(1),
Generators: map[string]generators.Generator{},
- ArgoDB: argodb,
+ ArgoDB: &dbmocks.ArgoDB{},
KubeClientset: kubeclientset,
Metrics: metrics,
}
- appStatuses, err := r.updateApplicationSetApplicationStatusProgress(t.Context(), log.NewEntry(log.StandardLogger()), &cc.appSet, cc.appSyncMap, cc.appStepMap)
+ appStatuses, err := r.updateApplicationSetApplicationStatusProgress(context.TODO(), log.NewEntry(log.StandardLogger()), &cc.appSet, cc.appSyncMap, cc.appStepMap)
// opt out of testing the LastTransitionTime is accurate
for i := range appStatuses {
@@ -6156,8 +6136,9 @@ func TestUpdateResourceStatus(t *testing.T) {
Sync: v1alpha1.SyncStatus{
Status: v1alpha1.SyncStatusCodeSynced,
},
- Health: v1alpha1.AppHealthStatus{
- Status: health.HealthStatusHealthy,
+ Health: v1alpha1.HealthStatus{
+ Status: health.HealthStatusHealthy,
+ Message: "OK",
},
},
},
@@ -6167,7 +6148,8 @@ func TestUpdateResourceStatus(t *testing.T) {
Name: "app1",
Status: v1alpha1.SyncStatusCodeSynced,
Health: &v1alpha1.HealthStatus{
- Status: health.HealthStatusHealthy,
+ Status: health.HealthStatusHealthy,
+ Message: "OK",
},
},
},
@@ -6185,7 +6167,8 @@ func TestUpdateResourceStatus(t *testing.T) {
Name: "app1",
Status: v1alpha1.SyncStatusCodeSynced,
Health: &v1alpha1.HealthStatus{
- Status: health.HealthStatusHealthy,
+ Status: health.HealthStatusHealthy,
+ Message: "OK",
},
},
},
@@ -6200,8 +6183,9 @@ func TestUpdateResourceStatus(t *testing.T) {
Sync: v1alpha1.SyncStatus{
Status: v1alpha1.SyncStatusCodeSynced,
},
- Health: v1alpha1.AppHealthStatus{
- Status: health.HealthStatusHealthy,
+ Health: v1alpha1.HealthStatus{
+ Status: health.HealthStatusHealthy,
+ Message: "OK",
},
},
},
@@ -6211,7 +6195,8 @@ func TestUpdateResourceStatus(t *testing.T) {
Name: "app1",
Status: v1alpha1.SyncStatusCodeSynced,
Health: &v1alpha1.HealthStatus{
- Status: health.HealthStatusHealthy,
+ Status: health.HealthStatusHealthy,
+ Message: "OK",
},
},
},
@@ -6245,8 +6230,9 @@ func TestUpdateResourceStatus(t *testing.T) {
Sync: v1alpha1.SyncStatus{
Status: v1alpha1.SyncStatusCodeSynced,
},
- Health: v1alpha1.AppHealthStatus{
- Status: health.HealthStatusHealthy,
+ Health: v1alpha1.HealthStatus{
+ Status: health.HealthStatusHealthy,
+ Message: "OK",
},
},
},
@@ -6256,7 +6242,8 @@ func TestUpdateResourceStatus(t *testing.T) {
Name: "app1",
Status: v1alpha1.SyncStatusCodeSynced,
Health: &v1alpha1.HealthStatus{
- Status: health.HealthStatusHealthy,
+ Status: health.HealthStatusHealthy,
+ Message: "OK",
},
},
},
@@ -6289,21 +6276,19 @@ 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()
-
- argodb := db.NewDB("argocd", settings.NewSettingsManager(t.Context(), kubeclientset, "argocd"), kubeclientset)
+ metrics := appsetmetrics.NewFakeAppsetMetrics(client)
r := ApplicationSetReconciler{
Client: client,
Scheme: scheme,
Recorder: record.NewFakeRecorder(1),
Generators: map[string]generators.Generator{},
- ArgoDB: argodb,
+ ArgoDB: &dbmocks.ArgoDB{},
KubeClientset: kubeclientset,
Metrics: metrics,
}
- err := r.updateResourcesStatus(t.Context(), log.NewEntry(log.StandardLogger()), &cc.appSet, cc.apps)
+ err := r.updateResourcesStatus(context.TODO(), log.NewEntry(log.StandardLogger()), &cc.appSet, cc.apps)
require.NoError(t, err, "expected no errors, but errors occurred")
assert.Equal(t, cc.expectedResources, cc.appSet.Status.Resources, "expected resources did not match actual")
@@ -6318,7 +6303,8 @@ func generateNAppResourceStatuses(n int) []v1alpha1.ResourceStatus {
Name: "app" + strconv.Itoa(i),
Status: v1alpha1.SyncStatusCodeSynced,
Health: &v1alpha1.HealthStatus{
- Status: health.HealthStatusHealthy,
+ Status: health.HealthStatusHealthy,
+ Message: "OK",
},
},
)
@@ -6337,8 +6323,9 @@ func generateNHealthyApps(n int) []v1alpha1.Application {
Sync: v1alpha1.SyncStatus{
Status: v1alpha1.SyncStatusCodeSynced,
},
- Health: v1alpha1.AppHealthStatus{
- Status: health.HealthStatusHealthy,
+ Health: v1alpha1.HealthStatus{
+ Status: health.HealthStatusHealthy,
+ Message: "OK",
},
},
})
@@ -6378,27 +6365,25 @@ 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()
-
- argodb := db.NewDB("argocd", settings.NewSettingsManager(t.Context(), kubeclientset, "argocd"), kubeclientset)
+ metrics := appsetmetrics.NewFakeAppsetMetrics(client)
r := ApplicationSetReconciler{
Client: client,
Scheme: scheme,
Recorder: record.NewFakeRecorder(1),
Generators: map[string]generators.Generator{},
- ArgoDB: argodb,
+ ArgoDB: &dbmocks.ArgoDB{},
KubeClientset: kubeclientset,
Metrics: metrics,
}
- err := r.updateResourcesStatus(t.Context(), log.NewEntry(log.StandardLogger()), &cc.appSet, cc.apps)
+ err := r.updateResourcesStatus(context.TODO(), log.NewEntry(log.StandardLogger()), &cc.appSet, cc.apps)
require.NoError(t, err, "expected no errors, but errors occurred")
- err = r.updateResourcesStatus(t.Context(), log.NewEntry(log.StandardLogger()), &cc.appSet, cc.apps)
+ err = r.updateResourcesStatus(context.TODO(), log.NewEntry(log.StandardLogger()), &cc.appSet, cc.apps)
require.NoError(t, err, "expected no errors, but errors occurred")
- err = r.updateResourcesStatus(t.Context(), log.NewEntry(log.StandardLogger()), &cc.appSet, cc.apps)
+ err = r.updateResourcesStatus(context.TODO(), log.NewEntry(log.StandardLogger()), &cc.appSet, cc.apps)
require.NoError(t, err, "expected no errors, but errors occurred")
assert.Equal(t, cc.expectedResources, cc.appSet.Status.Resources, "expected resources did not match actual")
@@ -6406,7 +6391,7 @@ func TestResourceStatusAreOrdered(t *testing.T) {
}
}
-func TestApplicationOwnsHandler(t *testing.T) {
+func TestOwnsHandler(t *testing.T) {
// progressive syncs do not affect create, delete, or generic
ownsHandler := getApplicationOwnsHandler(true)
assert.False(t, ownsHandler.CreateFunc(event.CreateEvent{}))
@@ -6442,12 +6427,12 @@ func TestApplicationOwnsHandler(t *testing.T) {
{name: "ApplicationHealthStatusDiff", args: args{
e: event.UpdateEvent{
ObjectOld: &v1alpha1.Application{Status: v1alpha1.ApplicationStatus{
- Health: v1alpha1.AppHealthStatus{
+ Health: v1alpha1.HealthStatus{
Status: "Unknown",
},
}},
ObjectNew: &v1alpha1.Application{Status: v1alpha1.ApplicationStatus{
- Health: v1alpha1.AppHealthStatus{
+ Health: v1alpha1.HealthStatus{
Status: "Healthy",
},
}},
@@ -6662,7 +6647,7 @@ func TestMigrateStatus(t *testing.T) {
Client: client,
}
- err := r.migrateStatus(t.Context(), &tc.appset)
+ err := r.migrateStatus(context.Background(), &tc.appset)
require.NoError(t, err)
assert.Equal(t, tc.expectedStatus, tc.appset.Status)
})
diff --git a/applicationset/controllers/clustereventhandler.go b/applicationset/controllers/clustereventhandler.go
index dd71e9b8c7..363fc03f16 100644
--- a/applicationset/controllers/clustereventhandler.go
+++ b/applicationset/controllers/clustereventhandler.go
@@ -14,8 +14,8 @@ import (
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/event"
- "github.com/argoproj/argo-cd/v3/common"
- argoprojiov1alpha1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/common"
+ argoprojiov1alpha1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
)
// clusterSecretEventHandler is used when watching Secrets to check if they are ArgoCD Cluster Secrets, and if so
diff --git a/applicationset/controllers/clustereventhandler_test.go b/applicationset/controllers/clustereventhandler_test.go
index 02b17551f6..8af4b1c17d 100644
--- a/applicationset/controllers/clustereventhandler_test.go
+++ b/applicationset/controllers/clustereventhandler_test.go
@@ -1,23 +1,24 @@
package controllers
import (
+ "context"
"testing"
- argocommon "github.com/argoproj/argo-cd/v3/common"
+ argocommon "github.com/argoproj/argo-cd/v2/common"
log "github.com/sirupsen/logrus"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
corev1 "k8s.io/api/core/v1"
apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+ v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client/fake"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
- argov1alpha1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ argov1alpha1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
)
func TestClusterEventHandler(t *testing.T) {
@@ -38,7 +39,7 @@ func TestClusterEventHandler(t *testing.T) {
name: "no application sets should mean no requests",
items: []argov1alpha1.ApplicationSet{},
secret: corev1.Secret{
- ObjectMeta: metav1.ObjectMeta{
+ ObjectMeta: v1.ObjectMeta{
Namespace: "argocd",
Name: "my-secret",
Labels: map[string]string{
@@ -52,7 +53,7 @@ func TestClusterEventHandler(t *testing.T) {
name: "a cluster generator should produce a request",
items: []argov1alpha1.ApplicationSet{
{
- ObjectMeta: metav1.ObjectMeta{
+ ObjectMeta: v1.ObjectMeta{
Name: "my-app-set",
Namespace: "argocd",
},
@@ -66,7 +67,7 @@ func TestClusterEventHandler(t *testing.T) {
},
},
secret: corev1.Secret{
- ObjectMeta: metav1.ObjectMeta{
+ ObjectMeta: v1.ObjectMeta{
Namespace: "argocd",
Name: "my-secret",
Labels: map[string]string{
@@ -82,7 +83,7 @@ func TestClusterEventHandler(t *testing.T) {
name: "multiple cluster generators should produce multiple requests",
items: []argov1alpha1.ApplicationSet{
{
- ObjectMeta: metav1.ObjectMeta{
+ ObjectMeta: v1.ObjectMeta{
Name: "my-app-set",
Namespace: "argocd",
},
@@ -95,7 +96,7 @@ func TestClusterEventHandler(t *testing.T) {
},
},
{
- ObjectMeta: metav1.ObjectMeta{
+ ObjectMeta: v1.ObjectMeta{
Name: "my-app-set2",
Namespace: "argocd",
},
@@ -109,7 +110,7 @@ func TestClusterEventHandler(t *testing.T) {
},
},
secret: corev1.Secret{
- ObjectMeta: metav1.ObjectMeta{
+ ObjectMeta: v1.ObjectMeta{
Namespace: "argocd",
Name: "my-secret",
Labels: map[string]string{
@@ -126,7 +127,7 @@ func TestClusterEventHandler(t *testing.T) {
name: "non-cluster generator should not match",
items: []argov1alpha1.ApplicationSet{
{
- ObjectMeta: metav1.ObjectMeta{
+ ObjectMeta: v1.ObjectMeta{
Name: "my-app-set",
Namespace: "another-namespace",
},
@@ -139,7 +140,7 @@ func TestClusterEventHandler(t *testing.T) {
},
},
{
- ObjectMeta: metav1.ObjectMeta{
+ ObjectMeta: v1.ObjectMeta{
Name: "app-set-non-cluster",
Namespace: "argocd",
},
@@ -153,7 +154,7 @@ func TestClusterEventHandler(t *testing.T) {
},
},
secret: corev1.Secret{
- ObjectMeta: metav1.ObjectMeta{
+ ObjectMeta: v1.ObjectMeta{
Namespace: "argocd",
Name: "my-secret",
Labels: map[string]string{
@@ -169,7 +170,7 @@ func TestClusterEventHandler(t *testing.T) {
name: "non-argo cd secret should not match",
items: []argov1alpha1.ApplicationSet{
{
- ObjectMeta: metav1.ObjectMeta{
+ ObjectMeta: v1.ObjectMeta{
Name: "my-app-set",
Namespace: "another-namespace",
},
@@ -183,7 +184,7 @@ func TestClusterEventHandler(t *testing.T) {
},
},
secret: corev1.Secret{
- ObjectMeta: metav1.ObjectMeta{
+ ObjectMeta: v1.ObjectMeta{
Namespace: "argocd",
Name: "my-non-argocd-secret",
},
@@ -194,7 +195,7 @@ func TestClusterEventHandler(t *testing.T) {
name: "a matrix generator with a cluster generator should produce a request",
items: []argov1alpha1.ApplicationSet{
{
- ObjectMeta: metav1.ObjectMeta{
+ ObjectMeta: v1.ObjectMeta{
Name: "my-app-set",
Namespace: "argocd",
},
@@ -214,7 +215,7 @@ func TestClusterEventHandler(t *testing.T) {
},
},
secret: corev1.Secret{
- ObjectMeta: metav1.ObjectMeta{
+ ObjectMeta: v1.ObjectMeta{
Namespace: "argocd",
Name: "my-secret",
Labels: map[string]string{
@@ -230,7 +231,7 @@ func TestClusterEventHandler(t *testing.T) {
name: "a matrix generator with non cluster generator should not match",
items: []argov1alpha1.ApplicationSet{
{
- ObjectMeta: metav1.ObjectMeta{
+ ObjectMeta: v1.ObjectMeta{
Name: "my-app-set",
Namespace: "argocd",
},
@@ -250,7 +251,7 @@ func TestClusterEventHandler(t *testing.T) {
},
},
secret: corev1.Secret{
- ObjectMeta: metav1.ObjectMeta{
+ ObjectMeta: v1.ObjectMeta{
Namespace: "argocd",
Name: "my-secret",
Labels: map[string]string{
@@ -264,7 +265,7 @@ func TestClusterEventHandler(t *testing.T) {
name: "a matrix generator with a nested matrix generator containing a cluster generator should produce a request",
items: []argov1alpha1.ApplicationSet{
{
- ObjectMeta: metav1.ObjectMeta{
+ ObjectMeta: v1.ObjectMeta{
Name: "my-app-set",
Namespace: "argocd",
},
@@ -300,7 +301,7 @@ func TestClusterEventHandler(t *testing.T) {
},
},
secret: corev1.Secret{
- ObjectMeta: metav1.ObjectMeta{
+ ObjectMeta: v1.ObjectMeta{
Namespace: "argocd",
Name: "my-secret",
Labels: map[string]string{
@@ -316,7 +317,7 @@ func TestClusterEventHandler(t *testing.T) {
name: "a matrix generator with a nested matrix generator containing non cluster generator should not match",
items: []argov1alpha1.ApplicationSet{
{
- ObjectMeta: metav1.ObjectMeta{
+ ObjectMeta: v1.ObjectMeta{
Name: "my-app-set",
Namespace: "argocd",
},
@@ -351,7 +352,7 @@ func TestClusterEventHandler(t *testing.T) {
},
},
secret: corev1.Secret{
- ObjectMeta: metav1.ObjectMeta{
+ ObjectMeta: v1.ObjectMeta{
Namespace: "argocd",
Name: "my-secret",
Labels: map[string]string{
@@ -365,7 +366,7 @@ func TestClusterEventHandler(t *testing.T) {
name: "a merge generator with a cluster generator should produce a request",
items: []argov1alpha1.ApplicationSet{
{
- ObjectMeta: metav1.ObjectMeta{
+ ObjectMeta: v1.ObjectMeta{
Name: "my-app-set",
Namespace: "argocd",
},
@@ -385,7 +386,7 @@ func TestClusterEventHandler(t *testing.T) {
},
},
secret: corev1.Secret{
- ObjectMeta: metav1.ObjectMeta{
+ ObjectMeta: v1.ObjectMeta{
Namespace: "argocd",
Name: "my-secret",
Labels: map[string]string{
@@ -401,7 +402,7 @@ func TestClusterEventHandler(t *testing.T) {
name: "a matrix generator with non cluster generator should not match",
items: []argov1alpha1.ApplicationSet{
{
- ObjectMeta: metav1.ObjectMeta{
+ ObjectMeta: v1.ObjectMeta{
Name: "my-app-set",
Namespace: "argocd",
},
@@ -421,7 +422,7 @@ func TestClusterEventHandler(t *testing.T) {
},
},
secret: corev1.Secret{
- ObjectMeta: metav1.ObjectMeta{
+ ObjectMeta: v1.ObjectMeta{
Namespace: "argocd",
Name: "my-secret",
Labels: map[string]string{
@@ -435,7 +436,7 @@ func TestClusterEventHandler(t *testing.T) {
name: "a merge generator with a nested merge generator containing a cluster generator should produce a request",
items: []argov1alpha1.ApplicationSet{
{
- ObjectMeta: metav1.ObjectMeta{
+ ObjectMeta: v1.ObjectMeta{
Name: "my-app-set",
Namespace: "argocd",
},
@@ -471,7 +472,7 @@ func TestClusterEventHandler(t *testing.T) {
},
},
secret: corev1.Secret{
- ObjectMeta: metav1.ObjectMeta{
+ ObjectMeta: v1.ObjectMeta{
Namespace: "argocd",
Name: "my-secret",
Labels: map[string]string{
@@ -487,7 +488,7 @@ func TestClusterEventHandler(t *testing.T) {
name: "a merge generator with a nested merge generator containing non cluster generator should not match",
items: []argov1alpha1.ApplicationSet{
{
- ObjectMeta: metav1.ObjectMeta{
+ ObjectMeta: v1.ObjectMeta{
Name: "my-app-set",
Namespace: "argocd",
},
@@ -522,7 +523,7 @@ func TestClusterEventHandler(t *testing.T) {
},
},
secret: corev1.Secret{
- ObjectMeta: metav1.ObjectMeta{
+ ObjectMeta: v1.ObjectMeta{
Namespace: "argocd",
Name: "my-secret",
Labels: map[string]string{
@@ -549,7 +550,7 @@ func TestClusterEventHandler(t *testing.T) {
mockAddRateLimitingInterface := mockAddRateLimitingInterface{}
- handler.queueRelatedAppGenerators(t.Context(), &mockAddRateLimitingInterface, &test.secret)
+ handler.queueRelatedAppGenerators(context.Background(), &mockAddRateLimitingInterface, &test.secret)
assert.ElementsMatch(t, mockAddRateLimitingInterface.addedItems, test.expectedRequests)
})
diff --git a/applicationset/controllers/requeue_after_test.go b/applicationset/controllers/requeue_after_test.go
index 5a2e033973..c0c039b88f 100644
--- a/applicationset/controllers/requeue_after_test.go
+++ b/applicationset/controllers/requeue_after_test.go
@@ -1,6 +1,7 @@
package controllers
import (
+ "context"
"testing"
"time"
@@ -15,15 +16,15 @@ import (
"k8s.io/client-go/tools/record"
"sigs.k8s.io/controller-runtime/pkg/client/fake"
- "github.com/argoproj/argo-cd/v3/applicationset/generators"
- appsetmetrics "github.com/argoproj/argo-cd/v3/applicationset/metrics"
- "github.com/argoproj/argo-cd/v3/applicationset/services/mocks"
- argov1alpha1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/applicationset/generators"
+ appsetmetrics "github.com/argoproj/argo-cd/v2/applicationset/metrics"
+ "github.com/argoproj/argo-cd/v2/applicationset/services/mocks"
+ argov1alpha1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
)
func TestRequeueAfter(t *testing.T) {
mockServer := &mocks.Repos{}
- ctx := t.Context()
+ ctx := context.Background()
scheme := runtime.NewScheme()
err := argov1alpha1.AddToScheme(scheme)
require.NoError(t, err)
@@ -35,20 +36,20 @@ func TestRequeueAfter(t *testing.T) {
appClientset := kubefake.NewSimpleClientset()
k8sClient := fake.NewClientBuilder().Build()
duckType := &unstructured.Unstructured{
- Object: map[string]any{
+ Object: map[string]interface{}{
"apiVersion": "v2quack",
"kind": "Duck",
- "metadata": map[string]any{
+ "metadata": map[string]interface{}{
"name": "mightyduck",
"namespace": "namespace",
- "labels": map[string]any{"duck": "all-species"},
+ "labels": map[string]interface{}{"duck": "all-species"},
},
- "status": map[string]any{
- "decisions": []any{
- map[string]any{
+ "status": map[string]interface{}{
+ "decisions": []interface{}{
+ map[string]interface{}{
"clusterName": "staging-01",
},
- map[string]any{
+ map[string]interface{}{
"clusterName": "production-01",
},
},
@@ -59,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(ctx, k8sClient, appClientset, "argocd"),
+ "Clusters": generators.NewClusterGenerator(k8sClient, ctx, appClientset, "argocd"),
"Git": generators.NewGitGenerator(mockServer, "namespace"),
"SCMProvider": generators.NewSCMProviderGenerator(fake.NewClientBuilder().WithObjects(&corev1.Secret{}).Build(), scmConfig),
"ClusterDecisionResource": generators.NewDuckTypeGenerator(ctx, fakeDynClient, appClientset, "argocd"),
@@ -89,7 +90,7 @@ func TestRequeueAfter(t *testing.T) {
}
client := fake.NewClientBuilder().WithScheme(scheme).Build()
- metrics := appsetmetrics.NewFakeAppsetMetrics()
+ metrics := appsetmetrics.NewFakeAppsetMetrics(client)
r := ApplicationSetReconciler{
Client: client,
Scheme: scheme,
@@ -129,7 +130,7 @@ func TestRequeueAfter(t *testing.T) {
}},
},
},
- }, ""}, want: generators.DefaultRequeueAfter, wantErr: assert.NoError},
+ }, ""}, want: generators.DefaultRequeueAfterSeconds, wantErr: assert.NoError},
{name: "ClusterMatrixNested", args: args{&argov1alpha1.ApplicationSet{
Spec: argov1alpha1.ApplicationSetSpec{
Generators: []argov1alpha1.ApplicationSetGenerator{
@@ -144,7 +145,7 @@ func TestRequeueAfter(t *testing.T) {
}},
},
},
- }, ""}, want: generators.DefaultRequeueAfter, wantErr: assert.NoError},
+ }, ""}, want: generators.DefaultRequeueAfterSeconds, wantErr: assert.NoError},
{name: "ListGenerator", args: args{appset: &argov1alpha1.ApplicationSet{
Spec: argov1alpha1.ApplicationSetSpec{
Generators: []argov1alpha1.ApplicationSetGenerator{{List: &argov1alpha1.ListGenerator{}}},
@@ -154,7 +155,7 @@ func TestRequeueAfter(t *testing.T) {
Spec: argov1alpha1.ApplicationSetSpec{
Generators: []argov1alpha1.ApplicationSetGenerator{{ClusterDecisionResource: &argov1alpha1.DuckTypeGenerator{}}},
},
- }}, want: generators.DefaultRequeueAfter, wantErr: assert.NoError},
+ }}, want: generators.DefaultRequeueAfterSeconds, wantErr: assert.NoError},
{name: "OverrideRequeueDuck", args: args{
appset: &argov1alpha1.ApplicationSet{
Spec: argov1alpha1.ApplicationSetSpec{
diff --git a/applicationset/controllers/template/patch.go b/applicationset/controllers/template/patch.go
index 0449815dbe..b9d1166f1f 100644
--- a/applicationset/controllers/template/patch.go
+++ b/applicationset/controllers/template/patch.go
@@ -6,8 +6,8 @@ import (
"k8s.io/apimachinery/pkg/util/strategicpatch"
- "github.com/argoproj/argo-cd/v3/applicationset/utils"
- appv1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/applicationset/utils"
+ appv1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
)
func applyTemplatePatch(app *appv1.Application, templatePatch string) (*appv1.Application, error) {
diff --git a/applicationset/controllers/template/patch_test.go b/applicationset/controllers/template/patch_test.go
index 35c88fe650..456fe44599 100644
--- a/applicationset/controllers/template/patch_test.go
+++ b/applicationset/controllers/template/patch_test.go
@@ -7,7 +7,7 @@ import (
"github.com/stretchr/testify/require"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
- appv1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ appv1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
)
func Test_ApplyTemplatePatch(t *testing.T) {
diff --git a/applicationset/controllers/template/template.go b/applicationset/controllers/template/template.go
index 4706402cb5..616b7ef9a7 100644
--- a/applicationset/controllers/template/template.go
+++ b/applicationset/controllers/template/template.go
@@ -7,10 +7,10 @@ import (
log "github.com/sirupsen/logrus"
- "github.com/argoproj/argo-cd/v3/applicationset/generators"
- "github.com/argoproj/argo-cd/v3/applicationset/utils"
+ "github.com/argoproj/argo-cd/v2/applicationset/generators"
+ "github.com/argoproj/argo-cd/v2/applicationset/utils"
- argov1alpha1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ argov1alpha1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
)
func GenerateApplications(logCtx *log.Entry, applicationSetInfo argov1alpha1.ApplicationSet, g map[string]generators.Generator, renderer utils.Renderer, client client.Client) ([]argov1alpha1.Application, argov1alpha1.ApplicationSetReasonType, error) {
@@ -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]any{}, client)
+ t, err := generators.Transform(requestedGenerator, g, applicationSetInfo.Spec.Template, &applicationSetInfo, map[string]interface{}{}, 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]any) (*argov1alpha1.Application, error) {
+func renderTemplatePatch(r utils.Renderer, app *argov1alpha1.Application, applicationSetInfo argov1alpha1.ApplicationSet, params map[string]interface{}) (*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 e3e7ffaa8e..27e2c17f10 100644
--- a/applicationset/controllers/template/template_test.go
+++ b/applicationset/controllers/template/template_test.go
@@ -1,7 +1,7 @@
package template
import (
- "errors"
+ "fmt"
"maps"
"testing"
@@ -13,12 +13,12 @@ import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
- "github.com/argoproj/argo-cd/v3/applicationset/generators"
- genmock "github.com/argoproj/argo-cd/v3/applicationset/generators/mocks"
- "github.com/argoproj/argo-cd/v3/applicationset/utils"
- rendmock "github.com/argoproj/argo-cd/v3/applicationset/utils/mocks"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/applicationset/generators"
+ genmock "github.com/argoproj/argo-cd/v2/applicationset/generators/mocks"
+ "github.com/argoproj/argo-cd/v2/applicationset/utils"
+ rendmock "github.com/argoproj/argo-cd/v2/applicationset/utils/mocks"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
)
func TestGenerateApplications(t *testing.T) {
@@ -31,7 +31,7 @@ func TestGenerateApplications(t *testing.T) {
for _, c := range []struct {
name string
- params []map[string]any
+ params []map[string]interface{}
template v1alpha1.ApplicationSetTemplate
generateParamsError error
rendererError error
@@ -40,7 +40,7 @@ func TestGenerateApplications(t *testing.T) {
}{
{
name: "Generate two applications",
- params: []map[string]any{{"name": "app1"}, {"name": "app2"}},
+ params: []map[string]interface{}{{"name": "app1"}, {"name": "app2"}},
template: v1alpha1.ApplicationSetTemplate{
ApplicationSetTemplateMeta: v1alpha1.ApplicationSetTemplateMeta{
Name: "name",
@@ -53,13 +53,13 @@ func TestGenerateApplications(t *testing.T) {
},
{
name: "Handles error from the generator",
- generateParamsError: errors.New("error"),
+ generateParamsError: fmt.Errorf("error"),
expectErr: true,
expectedReason: v1alpha1.ApplicationSetReasonApplicationParamsGenerationError,
},
{
name: "Handles error from the render",
- params: []map[string]any{{"name": "app1"}, {"name": "app2"}},
+ params: []map[string]interface{}{{"name": "app1"}, {"name": "app2"}},
template: v1alpha1.ApplicationSetTemplate{
ApplicationSetTemplateMeta: v1alpha1.ApplicationSetTemplateMeta{
Name: "name",
@@ -68,7 +68,7 @@ func TestGenerateApplications(t *testing.T) {
},
Spec: v1alpha1.ApplicationSpec{},
},
- rendererError: errors.New("error"),
+ rendererError: fmt.Errorf("error"),
expectErr: true,
expectedReason: v1alpha1.ApplicationSetReasonRenderTemplateParamsError,
},
@@ -153,7 +153,7 @@ func TestGenerateApplications(t *testing.T) {
func TestMergeTemplateApplications(t *testing.T) {
for _, c := range []struct {
name string
- params []map[string]any
+ params []map[string]interface{}
template v1alpha1.ApplicationSetTemplate
overrideTemplate v1alpha1.ApplicationSetTemplate
expectedMerged v1alpha1.ApplicationSetTemplate
@@ -161,7 +161,7 @@ func TestMergeTemplateApplications(t *testing.T) {
}{
{
name: "Generate app",
- params: []map[string]any{{"name": "app1"}},
+ params: []map[string]interface{}{{"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]any
+ params []map[string]interface{}
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]any{
+ params: []map[string]interface{}{
{
"number": "1",
"title": "title1",
@@ -341,10 +341,10 @@ func TestGenerateAppsUsingPullRequestGenerator(t *testing.T) {
renderer,
nil,
)
- assert.Equal(t, cases.expectedApp[0].Name, gotApp[0].Name)
- assert.Equal(t, cases.expectedApp[0].Spec.Source.TargetRevision, gotApp[0].Spec.Source.TargetRevision)
- assert.Equal(t, cases.expectedApp[0].Spec.Destination.Namespace, gotApp[0].Spec.Destination.Namespace)
- assert.True(t, maps.Equal(cases.expectedApp[0].Labels, gotApp[0].Labels))
+ assert.EqualValues(t, cases.expectedApp[0].ObjectMeta.Name, gotApp[0].ObjectMeta.Name)
+ assert.EqualValues(t, cases.expectedApp[0].Spec.Source.TargetRevision, gotApp[0].Spec.Source.TargetRevision)
+ assert.EqualValues(t, cases.expectedApp[0].Spec.Destination.Namespace, gotApp[0].Spec.Destination.Namespace)
+ assert.True(t, maps.Equal(cases.expectedApp[0].ObjectMeta.Labels, gotApp[0].ObjectMeta.Labels))
})
}
}
diff --git a/applicationset/examples/applications-sync-policies/guestbook/engineering-dev/guestbook-ui-deployment.yaml b/applicationset/examples/applications-sync-policies/guestbook/engineering-dev/guestbook-ui-deployment.yaml
index d0591f0831..8a0975e363 100644
--- a/applicationset/examples/applications-sync-policies/guestbook/engineering-dev/guestbook-ui-deployment.yaml
+++ b/applicationset/examples/applications-sync-policies/guestbook/engineering-dev/guestbook-ui-deployment.yaml
@@ -14,7 +14,7 @@ spec:
app: guestbook-ui
spec:
containers:
- - image: quay.io/argoprojlabs/argocd-e2e-container:0.2
+ - image: gcr.io/heptio-images/ks-guestbook-demo:0.2
name: guestbook-ui
ports:
- containerPort: 80
diff --git a/applicationset/examples/applications-sync-policies/guestbook/engineering-prod/guestbook-ui-deployment.yaml b/applicationset/examples/applications-sync-policies/guestbook/engineering-prod/guestbook-ui-deployment.yaml
index d0591f0831..8a0975e363 100644
--- a/applicationset/examples/applications-sync-policies/guestbook/engineering-prod/guestbook-ui-deployment.yaml
+++ b/applicationset/examples/applications-sync-policies/guestbook/engineering-prod/guestbook-ui-deployment.yaml
@@ -14,7 +14,7 @@ spec:
app: guestbook-ui
spec:
containers:
- - image: quay.io/argoprojlabs/argocd-e2e-container:0.2
+ - image: gcr.io/heptio-images/ks-guestbook-demo:0.2
name: guestbook-ui
ports:
- containerPort: 80
diff --git a/applicationset/examples/git-generator-directory/excludes/cluster-addons/exclude-helm-guestbook/values.yaml b/applicationset/examples/git-generator-directory/excludes/cluster-addons/exclude-helm-guestbook/values.yaml
index d0f2bf589b..3666712aec 100644
--- a/applicationset/examples/git-generator-directory/excludes/cluster-addons/exclude-helm-guestbook/values.yaml
+++ b/applicationset/examples/git-generator-directory/excludes/cluster-addons/exclude-helm-guestbook/values.yaml
@@ -5,7 +5,7 @@
replicaCount: 1
image:
- repository: quay.io/argoprojlabs/argocd-e2e-container
+ repository: gcr.io/heptio-images/ks-guestbook-demo
tag: 0.1
pullPolicy: IfNotPresent
diff --git a/applicationset/examples/git-generator-files-discovery/apps/guestbook/guestbook-ui-deployment.yaml b/applicationset/examples/git-generator-files-discovery/apps/guestbook/guestbook-ui-deployment.yaml
index d0591f0831..8a0975e363 100644
--- a/applicationset/examples/git-generator-files-discovery/apps/guestbook/guestbook-ui-deployment.yaml
+++ b/applicationset/examples/git-generator-files-discovery/apps/guestbook/guestbook-ui-deployment.yaml
@@ -14,7 +14,7 @@ spec:
app: guestbook-ui
spec:
containers:
- - image: quay.io/argoprojlabs/argocd-e2e-container:0.2
+ - image: gcr.io/heptio-images/ks-guestbook-demo:0.2
name: guestbook-ui
ports:
- containerPort: 80
diff --git a/applicationset/examples/git-generator-files-discovery/excludes/git-files-exclude-example-fasttemplate.yaml b/applicationset/examples/git-generator-files-discovery/excludes/git-files-exclude-example-fasttemplate.yaml
deleted file mode 100644
index 97b2cd3ad2..0000000000
--- a/applicationset/examples/git-generator-files-discovery/excludes/git-files-exclude-example-fasttemplate.yaml
+++ /dev/null
@@ -1,26 +0,0 @@
-apiVersion: argoproj.io/v1alpha1
-kind: ApplicationSet
-metadata:
- name: guestbook
-spec:
- generators:
- - git:
- repoURL: https://github.com/argoproj/argo-cd.git
- revision: HEAD
- files:
- - path: "applicationset/examples/git-generator-files-discovery/cluster-config/**/config.json"
- - path: "applicationset/examples/git-generator-files-discovery/cluster-config/*/dev/config.json"
- exclude: true
- template:
- metadata:
- name: '{{cluster.name}}-guestbook'
- spec:
- project: default
- source:
- repoURL: https://github.com/argoproj/argo-cd.git
- targetRevision: HEAD
- path: "applicationset/examples/git-generator-files-discovery/apps/guestbook"
- destination:
- server: https://kubernetes.default.svc
- #server: '{{cluster.address}}'
- namespace: guestbook
\ No newline at end of file
diff --git a/applicationset/examples/git-generator-files-discovery/excludes/git-files-exclude-example.yaml b/applicationset/examples/git-generator-files-discovery/excludes/git-files-exclude-example.yaml
deleted file mode 100644
index 0a17e42fa6..0000000000
--- a/applicationset/examples/git-generator-files-discovery/excludes/git-files-exclude-example.yaml
+++ /dev/null
@@ -1,27 +0,0 @@
-apiVersion: argoproj.io/v1alpha1
-kind: ApplicationSet
-metadata:
- name: guestbook
-spec:
- goTemplate: true
- goTemplateOptions: ["missingkey=error"]
- generators:
- - git:
- repoURL: https://github.com/argoproj/argo-cd.git
- revision: HEAD
- files:
- - path: "applicationset/examples/git-generator-files-discovery/cluster-config/**/config.json"
- - path: "applicationset/examples/git-generator-files-discovery/cluster-config/*/dev/config.json"
- exclude: true
- template:
- metadata:
- name: '{{.cluster.name}}-guestbook'
- spec:
- project: default
- source:
- repoURL: https://github.com/argoproj/argo-cd.git
- targetRevision: HEAD
- path: "applicationset/examples/git-generator-files-discovery/apps/guestbook"
- destination:
- server: https://kubernetes.default.svc
- namespace: guestbook
\ No newline at end of file
diff --git a/applicationset/examples/list-generator/guestbook/engineering-dev/guestbook-ui-deployment.yaml b/applicationset/examples/list-generator/guestbook/engineering-dev/guestbook-ui-deployment.yaml
index d0591f0831..8a0975e363 100644
--- a/applicationset/examples/list-generator/guestbook/engineering-dev/guestbook-ui-deployment.yaml
+++ b/applicationset/examples/list-generator/guestbook/engineering-dev/guestbook-ui-deployment.yaml
@@ -14,7 +14,7 @@ spec:
app: guestbook-ui
spec:
containers:
- - image: quay.io/argoprojlabs/argocd-e2e-container:0.2
+ - image: gcr.io/heptio-images/ks-guestbook-demo:0.2
name: guestbook-ui
ports:
- containerPort: 80
diff --git a/applicationset/examples/list-generator/guestbook/engineering-prod/guestbook-ui-deployment.yaml b/applicationset/examples/list-generator/guestbook/engineering-prod/guestbook-ui-deployment.yaml
index d0591f0831..8a0975e363 100644
--- a/applicationset/examples/list-generator/guestbook/engineering-prod/guestbook-ui-deployment.yaml
+++ b/applicationset/examples/list-generator/guestbook/engineering-prod/guestbook-ui-deployment.yaml
@@ -14,7 +14,7 @@ spec:
app: guestbook-ui
spec:
containers:
- - image: quay.io/argoprojlabs/argocd-e2e-container:0.2
+ - image: gcr.io/heptio-images/ks-guestbook-demo:0.2
name: guestbook-ui
ports:
- containerPort: 80
diff --git a/applicationset/examples/template-override/default/guestbook-ui-deployment.yaml b/applicationset/examples/template-override/default/guestbook-ui-deployment.yaml
index d0591f0831..8a0975e363 100644
--- a/applicationset/examples/template-override/default/guestbook-ui-deployment.yaml
+++ b/applicationset/examples/template-override/default/guestbook-ui-deployment.yaml
@@ -14,7 +14,7 @@ spec:
app: guestbook-ui
spec:
containers:
- - image: quay.io/argoprojlabs/argocd-e2e-container:0.2
+ - image: gcr.io/heptio-images/ks-guestbook-demo:0.2
name: guestbook-ui
ports:
- containerPort: 80
diff --git a/applicationset/examples/template-override/engineering-dev-override/guestbook-ui-deployment.yaml b/applicationset/examples/template-override/engineering-dev-override/guestbook-ui-deployment.yaml
index d0591f0831..8a0975e363 100644
--- a/applicationset/examples/template-override/engineering-dev-override/guestbook-ui-deployment.yaml
+++ b/applicationset/examples/template-override/engineering-dev-override/guestbook-ui-deployment.yaml
@@ -14,7 +14,7 @@ spec:
app: guestbook-ui
spec:
containers:
- - image: quay.io/argoprojlabs/argocd-e2e-container:0.2
+ - image: gcr.io/heptio-images/ks-guestbook-demo:0.2
name: guestbook-ui
ports:
- containerPort: 80
diff --git a/applicationset/generators/cluster.go b/applicationset/generators/cluster.go
index db9d8f0716..79765f7bb3 100644
--- a/applicationset/generators/cluster.go
+++ b/applicationset/generators/cluster.go
@@ -7,16 +7,16 @@ import (
log "github.com/sirupsen/logrus"
- "github.com/argoproj/argo-cd/v3/util/settings"
+ "github.com/argoproj/argo-cd/v2/util/settings"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"sigs.k8s.io/controller-runtime/pkg/client"
- "github.com/argoproj/argo-cd/v3/applicationset/utils"
- "github.com/argoproj/argo-cd/v3/common"
- argoappsetv1alpha1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/applicationset/utils"
+ "github.com/argoproj/argo-cd/v2/common"
+ argoappsetv1alpha1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
)
var _ Generator = (*ClusterGenerator)(nil)
@@ -33,7 +33,7 @@ type ClusterGenerator struct {
var render = &utils.Render{}
-func NewClusterGenerator(ctx context.Context, c client.Client, clientset kubernetes.Interface, namespace string) Generator {
+func NewClusterGenerator(c client.Client, ctx context.Context, clientset kubernetes.Interface, namespace string) Generator {
settingsManager := settings.NewSettingsManager(ctx, clientset, namespace)
g := &ClusterGenerator{
@@ -56,21 +56,21 @@ 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]any, error) {
+func (g *ClusterGenerator) GenerateParams(appSetGenerator *argoappsetv1alpha1.ApplicationSetGenerator, appSet *argoappsetv1alpha1.ApplicationSet, _ client.Client) ([]map[string]interface{}, error) {
logCtx := log.WithField("applicationset", appSet.GetName()).WithField("namespace", appSet.GetNamespace())
if appSetGenerator == nil {
- return nil, ErrEmptyAppSetGenerator
+ return nil, EmptyAppSetGeneratorError
}
if appSetGenerator.Clusters == nil {
- return nil, ErrEmptyAppSetGenerator
+ return nil, EmptyAppSetGeneratorError
}
// Do not include the local cluster in the cluster parameters IF there is a non-empty selector
// - Since local clusters do not have secrets, they do not have labels to match against
ignoreLocalClusters := len(appSetGenerator.Clusters.Selector.MatchExpressions) > 0 || len(appSetGenerator.Clusters.Selector.MatchLabels) > 0
- // ListCluster will include the local cluster in the list of clusters
+ // ListCluster from Argo CD's util/db package will include the local cluster in the list of clusters
clustersFromArgoCD, err := utils.ListClusters(g.ctx, g.clientset, g.namespace)
if err != nil {
return nil, fmt.Errorf("error listing clusters: %w", err)
@@ -85,22 +85,22 @@ func (g *ClusterGenerator) GenerateParams(appSetGenerator *argoappsetv1alpha1.Ap
return nil, fmt.Errorf("error getting cluster secrets: %w", err)
}
- res := []map[string]any{}
+ res := []map[string]interface{}{}
secretsFound := []corev1.Secret{}
isFlatMode := appSetGenerator.Clusters.FlatList
logCtx.Debugf("Using flat mode = %t for cluster generator", isFlatMode)
- clustersParams := make([]map[string]any, 0)
+ clustersParams := make([]map[string]interface{}, 0)
- for _, cluster := range clustersFromArgoCD {
+ for _, cluster := range clustersFromArgoCD.Items {
// If there is a secret for this cluster, then it's a non-local cluster, so it will be
// handled by the next step.
if secretForCluster, exists := clusterSecrets[cluster.Name]; exists {
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]any{}
+ params := map[string]interface{}{}
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]any{}
+ params := map[string]interface{}{}
params["name"] = string(cluster.Data["name"])
params["nameNormalized"] = utils.SanitizeName(string(cluster.Data["name"]))
@@ -137,23 +137,23 @@ func (g *ClusterGenerator) GenerateParams(appSetGenerator *argoappsetv1alpha1.Ap
}
if appSet.Spec.GoTemplate {
- meta := map[string]any{}
+ meta := map[string]interface{}{}
- if len(cluster.Annotations) > 0 {
- meta["annotations"] = cluster.Annotations
+ if len(cluster.ObjectMeta.Annotations) > 0 {
+ meta["annotations"] = cluster.ObjectMeta.Annotations
}
- if len(cluster.Labels) > 0 {
- meta["labels"] = cluster.Labels
+ if len(cluster.ObjectMeta.Labels) > 0 {
+ meta["labels"] = cluster.ObjectMeta.Labels
}
params["metadata"] = meta
} else {
- for key, value := range cluster.Annotations {
- params["metadata.annotations."+key] = value
+ for key, value := range cluster.ObjectMeta.Annotations {
+ params[fmt.Sprintf("metadata.annotations.%s", key)] = value
}
- for key, value := range cluster.Labels {
- params["metadata.labels."+key] = value
+ for key, value := range cluster.ObjectMeta.Labels {
+ params[fmt.Sprintf("metadata.labels.%s", key)] = value
}
}
@@ -172,7 +172,7 @@ func (g *ClusterGenerator) GenerateParams(appSetGenerator *argoappsetv1alpha1.Ap
}
if isFlatMode {
- res = append(res, map[string]any{
+ res = append(res, map[string]interface{}{
"clusters": clustersParams,
})
}
@@ -188,7 +188,7 @@ func (g *ClusterGenerator) getSecretsByClusterName(log *log.Entry, appSetGenerat
return nil, fmt.Errorf("error converting label selector: %w", err)
}
- if err := g.List(context.Background(), clusterSecretList, client.MatchingLabelsSelector{Selector: secretSelector}); err != nil {
+ if err := g.Client.List(context.Background(), clusterSecretList, client.MatchingLabelsSelector{Selector: secretSelector}); err != nil {
return nil, err
}
log.Debugf("clusters matching labels: %d", len(clusterSecretList.Items))
diff --git a/applicationset/generators/cluster_test.go b/applicationset/generators/cluster_test.go
index e774c84c1a..30d8cf0347 100644
--- a/applicationset/generators/cluster_test.go
+++ b/applicationset/generators/cluster_test.go
@@ -2,7 +2,7 @@ package generators
import (
"context"
- "errors"
+ "fmt"
"testing"
corev1 "k8s.io/api/core/v1"
@@ -13,8 +13,8 @@ import (
kubefake "k8s.io/client-go/kubernetes/fake"
- "github.com/argoproj/argo-cd/v3/applicationset/utils"
- argoprojiov1alpha1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/applicationset/utils"
+ argoprojiov1alpha1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
@@ -27,7 +27,7 @@ type possiblyErroringFakeCtrlRuntimeClient struct {
func (p *possiblyErroringFakeCtrlRuntimeClient) List(ctx context.Context, secretList client.ObjectList, opts ...client.ListOption) error {
if p.shouldError {
- return errors.New("could not list Secrets")
+ return fmt.Errorf("could not list Secrets")
}
return p.Client.List(ctx, secretList, opts...)
}
@@ -89,7 +89,7 @@ func TestGenerateParams(t *testing.T) {
selector metav1.LabelSelector
isFlatMode bool
values map[string]string
- expected []map[string]any
+ expected []map[string]interface{}
// 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]any{
+ }, expected: []map[string]interface{}{
{"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]any{
+ expected: []map[string]interface{}{
{
"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]any{
+ expected: []map[string]interface{}{
{
"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]any{
+ expected: []map[string]interface{}{
{
"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]any{
+ expected: []map[string]interface{}{
{
"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": "",
@@ -227,7 +227,7 @@ func TestGenerateParams(t *testing.T) {
values: nil,
expected: nil,
clientError: true,
- expectedError: errors.New("error getting cluster secrets: could not list Secrets"),
+ expectedError: fmt.Errorf("error getting cluster secrets: could not list Secrets"),
},
{
name: "flat mode without selectors",
@@ -242,9 +242,9 @@ func TestGenerateParams(t *testing.T) {
"aaa": "{{ server }}",
"no-op": "{{ this-does-not-exist }}",
},
- expected: []map[string]any{
+ expected: []map[string]interface{}{
{
- "clusters": []map[string]any{
+ "clusters": []map[string]interface{}{
{"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]any{
+ expected: []map[string]interface{}{
{
- "clusters": []map[string]any{
+ "clusters": []map[string]interface{}{
{
"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",
@@ -315,7 +315,7 @@ func TestGenerateParams(t *testing.T) {
testCase.clientError,
}
- clusterGenerator := NewClusterGenerator(t.Context(), cl, appClientset, "namespace")
+ clusterGenerator := NewClusterGenerator(cl, context.Background(), appClientset, "namespace")
applicationSetInfo := argoprojiov1alpha1.ApplicationSet{
ObjectMeta: metav1.ObjectMeta{
@@ -398,7 +398,7 @@ func TestGenerateParamsGoTemplate(t *testing.T) {
selector metav1.LabelSelector
values map[string]string
isFlatMode bool
- expected []map[string]any
+ expected []map[string]interface{}
// 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]any{
+ }, expected: []map[string]interface{}{
{
"name": "production_01/west",
"nameNormalized": "production-01-west",
"server": "https://production-01.example.com",
"project": "",
- "metadata": map[string]any{
+ "metadata": map[string]interface{}{
"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]any{
+ "metadata": map[string]interface{}{
"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]any{
+ expected: []map[string]interface{}{
{
"name": "production_01/west",
"nameNormalized": "production-01-west",
"server": "https://production-01.example.com",
"project": "",
- "metadata": map[string]any{
+ "metadata": map[string]interface{}{
"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]any{
+ "metadata": map[string]interface{}{
"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]any{
+ expected: []map[string]interface{}{
{
"name": "production_01/west",
"nameNormalized": "production-01-west",
"server": "https://production-01.example.com",
"project": "",
- "metadata": map[string]any{
+ "metadata": map[string]interface{}{
"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]any{
+ expected: []map[string]interface{}{
{
"name": "production_01/west",
"nameNormalized": "production-01-west",
"server": "https://production-01.example.com",
"project": "",
- "metadata": map[string]any{
+ "metadata": map[string]interface{}{
"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]any{
+ "metadata": map[string]interface{}{
"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]any{
+ expected: []map[string]interface{}{
{
"name": "staging-01",
"nameNormalized": "staging-01",
"server": "https://staging-01.example.com",
"project": "",
- "metadata": map[string]any{
+ "metadata": map[string]interface{}{
"labels": map[string]string{
"argocd.argoproj.io/secret-type": "cluster",
"environment": "staging",
@@ -677,7 +677,7 @@ func TestGenerateParamsGoTemplate(t *testing.T) {
values: nil,
expected: nil,
clientError: true,
- expectedError: errors.New("error getting cluster secrets: could not list Secrets"),
+ expectedError: fmt.Errorf("error getting cluster secrets: could not list Secrets"),
},
{
name: "Clusters with flat list mode and no selector",
@@ -693,9 +693,9 @@ func TestGenerateParamsGoTemplate(t *testing.T) {
"aaa": "{{ .server }}",
"no-op": "{{ .thisDoesNotExist }}",
},
- expected: []map[string]any{
+ expected: []map[string]interface{}{
{
- "clusters": []map[string]any{
+ "clusters": []map[string]interface{}{
{
"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]any{
+ "metadata": map[string]interface{}{
"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]any{
+ "metadata": map[string]interface{}{
"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]any{
+ expected: []map[string]interface{}{
{
- "clusters": []map[string]any{
+ "clusters": []map[string]interface{}{
{
"name": "production_01/west",
"nameNormalized": "production-01-west",
"server": "https://production-01.example.com",
"project": "",
- "metadata": map[string]any{
+ "metadata": map[string]interface{}{
"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]any{
+ "metadata": map[string]interface{}{
"labels": map[string]string{
"argocd.argoproj.io/secret-type": "cluster",
"environment": "staging",
@@ -853,7 +853,7 @@ func TestGenerateParamsGoTemplate(t *testing.T) {
testCase.clientError,
}
- clusterGenerator := NewClusterGenerator(t.Context(), cl, appClientset, "namespace")
+ clusterGenerator := NewClusterGenerator(cl, context.Background(), appClientset, "namespace")
applicationSetInfo := argoprojiov1alpha1.ApplicationSet{
ObjectMeta: metav1.ObjectMeta{
diff --git a/applicationset/generators/duck_type.go b/applicationset/generators/duck_type.go
index 64b7b55eca..7bd78a0714 100644
--- a/applicationset/generators/duck_type.go
+++ b/applicationset/generators/duck_type.go
@@ -2,7 +2,6 @@ package generators
import (
"context"
- "errors"
"fmt"
"strings"
"time"
@@ -10,7 +9,7 @@ import (
log "github.com/sirupsen/logrus"
"sigs.k8s.io/controller-runtime/pkg/client"
- "github.com/argoproj/argo-cd/v3/util/settings"
+ "github.com/argoproj/argo-cd/v2/util/settings"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
@@ -18,8 +17,8 @@ import (
"k8s.io/client-go/dynamic"
"k8s.io/client-go/kubernetes"
- "github.com/argoproj/argo-cd/v3/applicationset/utils"
- argoprojiov1alpha1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/applicationset/utils"
+ argoprojiov1alpha1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
)
var _ Generator = (*DuckTypeGenerator)(nil)
@@ -60,14 +59,14 @@ 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]any, error) {
+func (g *DuckTypeGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator, appSet *argoprojiov1alpha1.ApplicationSet, _ client.Client) ([]map[string]interface{}, error) {
if appSetGenerator == nil {
- return nil, ErrEmptyAppSetGenerator
+ return nil, EmptyAppSetGeneratorError
}
// Not likely to happen
if appSetGenerator.ClusterDecisionResource == nil {
- return nil, ErrEmptyAppSetGenerator
+ return nil, EmptyAppSetGeneratorError
}
// ListCluster from Argo CD's util/db package will include the local cluster in the list of clusters
@@ -97,13 +96,13 @@ func (g *DuckTypeGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha1.A
// Validate the fields
if kind == "" || versionIdx < 1 {
log.Warningf("kind=%v, resourceName=%v, versionIdx=%v", kind, resourceName, versionIdx)
- return nil, errors.New("there is a problem with the apiVersion, kind or resourceName provided")
+ return nil, fmt.Errorf("There is a problem with the apiVersion, kind or resourceName provided")
}
if (resourceName == "" && labelSelector.MatchLabels == nil && labelSelector.MatchExpressions == nil) ||
(resourceName != "" && (labelSelector.MatchExpressions != nil || labelSelector.MatchLabels != nil)) {
log.Warningf("You must choose either resourceName=%v, labelSelector.matchLabels=%v or labelSelect.matchExpressions=%v", resourceName, labelSelector.MatchLabels, labelSelector.MatchExpressions)
- return nil, errors.New("there is a problem with the definition of the ClusterDecisionResource generator")
+ return nil, fmt.Errorf("There is a problem with the definition of the ClusterDecisionResource generator")
}
// Split up the apiVersion
@@ -131,7 +130,7 @@ func (g *DuckTypeGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha1.A
if len(duckResources.Items) == 0 {
log.Warning("no resource found, make sure you clusterDecisionResource is defined correctly")
- return nil, errors.New("no clusterDecisionResources found")
+ return nil, fmt.Errorf("no clusterDecisionResources found")
}
// Override the duck type in the status of the resource
@@ -147,77 +146,81 @@ func (g *DuckTypeGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha1.A
return nil, nil
}
- res := []map[string]any{}
- clusterDecisions := []any{}
+ res := []map[string]interface{}{}
+ clusterDecisions := []interface{}{}
// 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]any)) == 0 {
+ if duckResource.Object["status"] == nil || len(duckResource.Object["status"].(map[string]interface{})) == 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]any)[statusListKey].([]any)...)
+ clusterDecisions = append(clusterDecisions, duckResource.Object["status"].(map[string]interface{})[statusListKey].([]interface{})...)
}
log.Infof("Number of decisions found: %v", len(clusterDecisions))
- if len(clusterDecisions) == 0 {
+ // Read this outside the loop to improve performance
+ argoClusters := clustersFromArgoCD.Items
+
+ if len(clusterDecisions) > 0 {
+ for _, cluster := range clusterDecisions {
+ // generated instance of cluster params
+ params := map[string]interface{}{}
+
+ log.Infof("cluster: %v", cluster)
+ matchValue := cluster.(map[string]interface{})[matchKey]
+ if matchValue == nil || matchValue.(string) == "" {
+ log.Warningf("matchKey=%v not found in \"%v\" list: %v\n", matchKey, statusListKey, cluster.(map[string]interface{}))
+ continue
+ }
+
+ strMatchValue := matchValue.(string)
+ log.WithField(matchKey, strMatchValue).Debug("validate against ArgoCD")
+
+ found := false
+
+ for _, argoCluster := range argoClusters {
+ if argoCluster.Name == strMatchValue {
+ log.WithField(matchKey, argoCluster.Name).Info("matched cluster in ArgoCD")
+ params["name"] = argoCluster.Name
+ params["server"] = argoCluster.Server
+
+ found = true
+ break // Stop looking
+ }
+ }
+
+ if !found {
+ log.WithField(matchKey, strMatchValue).Warning("unmatched cluster in ArgoCD")
+ continue
+ }
+
+ for key, value := range cluster.(map[string]interface{}) {
+ params[key] = value.(string)
+ }
+
+ for key, value := range appSetGenerator.ClusterDecisionResource.Values {
+ if appSet.Spec.GoTemplate {
+ if params["values"] == nil {
+ params["values"] = map[string]string{}
+ }
+ params["values"].(map[string]string)[key] = value
+ } else {
+ params[fmt.Sprintf("values.%s", key)] = value
+ }
+ }
+
+ res = append(res, params)
+ }
+ } else {
log.Warningf("clusterDecisionResource status.%s missing", statusListKey)
return nil, nil
}
- for _, cluster := range clusterDecisions {
- // generated instance of cluster params
- params := map[string]any{}
-
- log.Infof("cluster: %v", cluster)
- 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]any))
- continue
- }
-
- strMatchValue := matchValue.(string)
- log.WithField(matchKey, strMatchValue).Debug("validate against ArgoCD")
-
- found := false
-
- for _, argoCluster := range clustersFromArgoCD {
- if argoCluster.Name == strMatchValue {
- log.WithField(matchKey, argoCluster.Name).Info("matched cluster in ArgoCD")
- params["name"] = argoCluster.Name
- params["server"] = argoCluster.Server
-
- found = true
- break // Stop looking
- }
- }
-
- if !found {
- log.WithField(matchKey, strMatchValue).Warning("unmatched cluster in ArgoCD")
- continue
- }
-
- for key, value := range cluster.(map[string]any) {
- params[key] = value.(string)
- }
-
- for key, value := range appSetGenerator.ClusterDecisionResource.Values {
- if appSet.Spec.GoTemplate {
- if params["values"] == nil {
- params["values"] = map[string]string{}
- }
- params["values"].(map[string]string)[key] = value
- } else {
- params["values."+key] = value
- }
- }
-
- res = append(res, params)
- }
return res, nil
}
diff --git a/applicationset/generators/duck_type_test.go b/applicationset/generators/duck_type_test.go
index 3d52d7fe0f..d2cfdbc59d 100644
--- a/applicationset/generators/duck_type_test.go
+++ b/applicationset/generators/duck_type_test.go
@@ -1,7 +1,8 @@
package generators
import (
- "errors"
+ "context"
+ "fmt"
"testing"
"github.com/stretchr/testify/assert"
@@ -15,11 +16,11 @@ import (
kubefake "k8s.io/client-go/kubernetes/fake"
"sigs.k8s.io/controller-runtime/pkg/client"
- argoprojiov1alpha1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ argoprojiov1alpha1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
)
const (
- resourceAPIVersion = "mallard.io/v1"
+ resourceApiVersion = "mallard.io/v1"
resourceKind = "ducks"
resourceName = "quak"
)
@@ -77,20 +78,20 @@ func TestGenerateParamsForDuckType(t *testing.T) {
}
duckType := &unstructured.Unstructured{
- Object: map[string]any{
- "apiVersion": resourceAPIVersion,
+ Object: map[string]interface{}{
+ "apiVersion": resourceApiVersion,
"kind": "Duck",
- "metadata": map[string]any{
+ "metadata": map[string]interface{}{
"name": resourceName,
"namespace": "namespace",
- "labels": map[string]any{"duck": "all-species"},
+ "labels": map[string]interface{}{"duck": "all-species"},
},
- "status": map[string]any{
- "decisions": []any{
- map[string]any{
+ "status": map[string]interface{}{
+ "decisions": []interface{}{
+ map[string]interface{}{
"clusterName": "staging-01",
},
- map[string]any{
+ map[string]interface{}{
"clusterName": "production-01",
},
},
@@ -99,17 +100,17 @@ func TestGenerateParamsForDuckType(t *testing.T) {
}
duckTypeProdOnly := &unstructured.Unstructured{
- Object: map[string]any{
- "apiVersion": resourceAPIVersion,
+ Object: map[string]interface{}{
+ "apiVersion": resourceApiVersion,
"kind": "Duck",
- "metadata": map[string]any{
+ "metadata": map[string]interface{}{
"name": resourceName,
"namespace": "namespace",
- "labels": map[string]any{"duck": "spotted"},
+ "labels": map[string]interface{}{"duck": "spotted"},
},
- "status": map[string]any{
- "decisions": []any{
- map[string]any{
+ "status": map[string]interface{}{
+ "decisions": []interface{}{
+ map[string]interface{}{
"clusterName": "production-01",
},
},
@@ -118,15 +119,15 @@ func TestGenerateParamsForDuckType(t *testing.T) {
}
duckTypeEmpty := &unstructured.Unstructured{
- Object: map[string]any{
- "apiVersion": resourceAPIVersion,
+ Object: map[string]interface{}{
+ "apiVersion": resourceApiVersion,
"kind": "Duck",
- "metadata": map[string]any{
+ "metadata": map[string]interface{}{
"name": resourceName,
"namespace": "namespace",
- "labels": map[string]any{"duck": "canvasback"},
+ "labels": map[string]interface{}{"duck": "canvasback"},
},
- "status": map[string]any{},
+ "status": map[string]interface{}{},
},
}
@@ -136,7 +137,7 @@ func TestGenerateParamsForDuckType(t *testing.T) {
Namespace: "namespace",
},
Data: map[string]string{
- "apiVersion": resourceAPIVersion,
+ "apiVersion": resourceApiVersion,
"kind": resourceKind,
"statusListKey": "decisions",
"matchKey": "clusterName",
@@ -150,7 +151,7 @@ func TestGenerateParamsForDuckType(t *testing.T) {
labelSelector metav1.LabelSelector
resource *unstructured.Unstructured
values map[string]string
- expected []map[string]any
+ expected []map[string]interface{}
expectedError error
}{
{
@@ -158,8 +159,8 @@ func TestGenerateParamsForDuckType(t *testing.T) {
resourceName: "",
resource: duckType,
values: nil,
- expected: []map[string]any{},
- expectedError: errors.New("there is a problem with the definition of the ClusterDecisionResource generator"),
+ expected: []map[string]interface{}{},
+ expectedError: fmt.Errorf("There is a problem with the definition of the ClusterDecisionResource generator"),
},
/*** This does not work with the FAKE runtime client, fieldSelectors are broken.
{
@@ -176,7 +177,7 @@ func TestGenerateParamsForDuckType(t *testing.T) {
resourceName: resourceName,
resource: duckType,
values: nil,
- expected: []map[string]any{
+ expected: []map[string]interface{}{
{"clusterName": "production-01", "name": "production-01", "server": "https://production-01.example.com"},
{"clusterName": "staging-01", "name": "staging-01", "server": "https://staging-01.example.com"},
@@ -190,7 +191,7 @@ func TestGenerateParamsForDuckType(t *testing.T) {
values: map[string]string{
"foo": "bar",
},
- expected: []map[string]any{
+ expected: []map[string]interface{}{
{"clusterName": "production-01", "values.foo": "bar", "name": "production-01", "server": "https://production-01.example.com"},
},
expectedError: nil,
@@ -218,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]any{
+ expected: []map[string]interface{}{
{"clusterName": "production-01", "name": "production-01", "server": "https://production-01.example.com"},
{"clusterName": "staging-01", "name": "staging-01", "server": "https://staging-01.example.com"},
@@ -233,7 +234,7 @@ func TestGenerateParamsForDuckType(t *testing.T) {
values: map[string]string{
"foo": "bar",
},
- expected: []map[string]any{
+ expected: []map[string]interface{}{
{"clusterName": "production-01", "values.foo": "bar", "name": "production-01", "server": "https://production-01.example.com"},
},
expectedError: nil,
@@ -250,7 +251,7 @@ func TestGenerateParamsForDuckType(t *testing.T) {
}},
resource: duckType,
values: nil,
- expected: []map[string]any{
+ expected: []map[string]interface{}{
{"clusterName": "production-01", "name": "production-01", "server": "https://production-01.example.com"},
{"clusterName": "staging-01", "name": "staging-01", "server": "https://staging-01.example.com"},
@@ -270,7 +271,7 @@ func TestGenerateParamsForDuckType(t *testing.T) {
resource: duckType,
values: nil,
expected: nil,
- expectedError: errors.New("there is a problem with the definition of the ClusterDecisionResource generator"),
+ expectedError: fmt.Errorf("There is a problem with the definition of the ClusterDecisionResource generator"),
},
}
@@ -292,7 +293,7 @@ func TestGenerateParamsForDuckType(t *testing.T) {
fakeDynClient := dynfake.NewSimpleDynamicClientWithCustomListKinds(runtime.NewScheme(), gvrToListKind, testCase.resource)
- duckTypeGenerator := NewDuckTypeGenerator(t.Context(), fakeDynClient, appClientset, "namespace")
+ duckTypeGenerator := NewDuckTypeGenerator(context.Background(), fakeDynClient, appClientset, "namespace")
applicationSetInfo := argoprojiov1alpha1.ApplicationSet{
ObjectMeta: metav1.ObjectMeta{
@@ -373,20 +374,20 @@ func TestGenerateParamsForDuckTypeGoTemplate(t *testing.T) {
}
duckType := &unstructured.Unstructured{
- Object: map[string]any{
- "apiVersion": resourceAPIVersion,
+ Object: map[string]interface{}{
+ "apiVersion": resourceApiVersion,
"kind": "Duck",
- "metadata": map[string]any{
+ "metadata": map[string]interface{}{
"name": resourceName,
"namespace": "namespace",
- "labels": map[string]any{"duck": "all-species"},
+ "labels": map[string]interface{}{"duck": "all-species"},
},
- "status": map[string]any{
- "decisions": []any{
- map[string]any{
+ "status": map[string]interface{}{
+ "decisions": []interface{}{
+ map[string]interface{}{
"clusterName": "staging-01",
},
- map[string]any{
+ map[string]interface{}{
"clusterName": "production-01",
},
},
@@ -395,17 +396,17 @@ func TestGenerateParamsForDuckTypeGoTemplate(t *testing.T) {
}
duckTypeProdOnly := &unstructured.Unstructured{
- Object: map[string]any{
- "apiVersion": resourceAPIVersion,
+ Object: map[string]interface{}{
+ "apiVersion": resourceApiVersion,
"kind": "Duck",
- "metadata": map[string]any{
+ "metadata": map[string]interface{}{
"name": resourceName,
"namespace": "namespace",
- "labels": map[string]any{"duck": "spotted"},
+ "labels": map[string]interface{}{"duck": "spotted"},
},
- "status": map[string]any{
- "decisions": []any{
- map[string]any{
+ "status": map[string]interface{}{
+ "decisions": []interface{}{
+ map[string]interface{}{
"clusterName": "production-01",
},
},
@@ -414,15 +415,15 @@ func TestGenerateParamsForDuckTypeGoTemplate(t *testing.T) {
}
duckTypeEmpty := &unstructured.Unstructured{
- Object: map[string]any{
- "apiVersion": resourceAPIVersion,
+ Object: map[string]interface{}{
+ "apiVersion": resourceApiVersion,
"kind": "Duck",
- "metadata": map[string]any{
+ "metadata": map[string]interface{}{
"name": resourceName,
"namespace": "namespace",
- "labels": map[string]any{"duck": "canvasback"},
+ "labels": map[string]interface{}{"duck": "canvasback"},
},
- "status": map[string]any{},
+ "status": map[string]interface{}{},
},
}
@@ -432,7 +433,7 @@ func TestGenerateParamsForDuckTypeGoTemplate(t *testing.T) {
Namespace: "namespace",
},
Data: map[string]string{
- "apiVersion": resourceAPIVersion,
+ "apiVersion": resourceApiVersion,
"kind": resourceKind,
"statusListKey": "decisions",
"matchKey": "clusterName",
@@ -446,7 +447,7 @@ func TestGenerateParamsForDuckTypeGoTemplate(t *testing.T) {
labelSelector metav1.LabelSelector
resource *unstructured.Unstructured
values map[string]string
- expected []map[string]any
+ expected []map[string]interface{}
expectedError error
}{
{
@@ -454,8 +455,8 @@ func TestGenerateParamsForDuckTypeGoTemplate(t *testing.T) {
resourceName: "",
resource: duckType,
values: nil,
- expected: []map[string]any{},
- expectedError: errors.New("there is a problem with the definition of the ClusterDecisionResource generator"),
+ expected: []map[string]interface{}{},
+ expectedError: fmt.Errorf("There is a problem with the definition of the ClusterDecisionResource generator"),
},
/*** This does not work with the FAKE runtime client, fieldSelectors are broken.
{
@@ -472,7 +473,7 @@ func TestGenerateParamsForDuckTypeGoTemplate(t *testing.T) {
resourceName: resourceName,
resource: duckType,
values: nil,
- expected: []map[string]any{
+ expected: []map[string]interface{}{
{"clusterName": "production-01", "name": "production-01", "server": "https://production-01.example.com"},
{"clusterName": "staging-01", "name": "staging-01", "server": "https://staging-01.example.com"},
@@ -486,7 +487,7 @@ func TestGenerateParamsForDuckTypeGoTemplate(t *testing.T) {
values: map[string]string{
"foo": "bar",
},
- expected: []map[string]any{
+ expected: []map[string]interface{}{
{"clusterName": "production-01", "values": map[string]string{"foo": "bar"}, "name": "production-01", "server": "https://production-01.example.com"},
},
expectedError: nil,
@@ -514,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]any{
+ expected: []map[string]interface{}{
{"clusterName": "production-01", "name": "production-01", "server": "https://production-01.example.com"},
{"clusterName": "staging-01", "name": "staging-01", "server": "https://staging-01.example.com"},
@@ -529,7 +530,7 @@ func TestGenerateParamsForDuckTypeGoTemplate(t *testing.T) {
values: map[string]string{
"foo": "bar",
},
- expected: []map[string]any{
+ expected: []map[string]interface{}{
{"clusterName": "production-01", "values": map[string]string{"foo": "bar"}, "name": "production-01", "server": "https://production-01.example.com"},
},
expectedError: nil,
@@ -546,7 +547,7 @@ func TestGenerateParamsForDuckTypeGoTemplate(t *testing.T) {
}},
resource: duckType,
values: nil,
- expected: []map[string]any{
+ expected: []map[string]interface{}{
{"clusterName": "production-01", "name": "production-01", "server": "https://production-01.example.com"},
{"clusterName": "staging-01", "name": "staging-01", "server": "https://staging-01.example.com"},
@@ -566,7 +567,7 @@ func TestGenerateParamsForDuckTypeGoTemplate(t *testing.T) {
resource: duckType,
values: nil,
expected: nil,
- expectedError: errors.New("there is a problem with the definition of the ClusterDecisionResource generator"),
+ expectedError: fmt.Errorf("There is a problem with the definition of the ClusterDecisionResource generator"),
},
}
@@ -588,7 +589,7 @@ func TestGenerateParamsForDuckTypeGoTemplate(t *testing.T) {
fakeDynClient := dynfake.NewSimpleDynamicClientWithCustomListKinds(runtime.NewScheme(), gvrToListKind, testCase.resource)
- duckTypeGenerator := NewDuckTypeGenerator(t.Context(), fakeDynClient, appClientset, "namespace")
+ duckTypeGenerator := NewDuckTypeGenerator(context.Background(), fakeDynClient, appClientset, "namespace")
applicationSetInfo := argoprojiov1alpha1.ApplicationSet{
ObjectMeta: metav1.ObjectMeta{
diff --git a/applicationset/generators/generator_spec_processor.go b/applicationset/generators/generator_spec_processor.go
index 392fd4b85f..25e6b138da 100644
--- a/applicationset/generators/generator_spec_processor.go
+++ b/applicationset/generators/generator_spec_processor.go
@@ -7,13 +7,13 @@ import (
"github.com/jeremywohl/flatten"
"sigs.k8s.io/controller-runtime/pkg/client"
- "github.com/argoproj/argo-cd/v3/applicationset/utils"
+ "github.com/argoproj/argo-cd/v2/applicationset/utils"
"k8s.io/apimachinery/pkg/labels"
- argoprojiov1alpha1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ argoprojiov1alpha1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
- "dario.cat/mergo"
+ "github.com/imdario/mergo"
log "github.com/sirupsen/logrus"
)
@@ -22,12 +22,12 @@ const (
)
type TransformResult struct {
- Params []map[string]any
+ Params []map[string]interface{}
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]any, client client.Client) ([]TransformResult, error) {
+func Transform(requestedGenerator argoprojiov1alpha1.ApplicationSetGenerator, allGenerators map[string]Generator, baseTemplate argoprojiov1alpha1.ApplicationSetTemplate, appSet *argoprojiov1alpha1.ApplicationSet, genParams map[string]interface{}, 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]any
+ var params []map[string]interface{}
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]any
+ var filterParams []map[string]interface{}
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]any) (map[string]string, error) {
+func flattenParameters(in map[string]interface{}) (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]any, useGoTemplate bool, goTemplateOptions []string) (argoprojiov1alpha1.ApplicationSetGenerator, error) {
+func InterpolateGenerator(requestedGenerator *argoprojiov1alpha1.ApplicationSetGenerator, params map[string]interface{}, useGoTemplate bool, goTemplateOptions []string) (argoprojiov1alpha1.ApplicationSetGenerator, error) {
render := utils.Render{}
interpolatedGenerator, err := render.RenderGeneratorParams(requestedGenerator, params, useGoTemplate, goTemplateOptions)
if err != nil {
@@ -159,3 +159,16 @@ func InterpolateGenerator(requestedGenerator *argoprojiov1alpha1.ApplicationSetG
return *interpolatedGenerator, nil
}
+
+// Fixes https://github.com/argoproj/argo-cd/issues/11982 while ensuring backwards compatibility.
+// This is only a short-term solution and should be removed in a future major version.
+func dropDisabledNestedSelectors(generators []argoprojiov1alpha1.ApplicationSetNestedGenerator) bool {
+ var foundSelector bool
+ for i := range generators {
+ if generators[i].Selector != nil {
+ foundSelector = true
+ generators[i].Selector = nil
+ }
+ }
+ return foundSelector
+}
diff --git a/applicationset/generators/generator_spec_processor_test.go b/applicationset/generators/generator_spec_processor_test.go
index 4f4be79fae..2c55fecad5 100644
--- a/applicationset/generators/generator_spec_processor_test.go
+++ b/applicationset/generators/generator_spec_processor_test.go
@@ -10,9 +10,9 @@ import (
apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
- "github.com/argoproj/argo-cd/v3/applicationset/services/mocks"
+ "github.com/argoproj/argo-cd/v2/applicationset/services/mocks"
- argov1alpha1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ argov1alpha1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
"github.com/stretchr/testify/mock"
corev1 "k8s.io/api/core/v1"
@@ -27,19 +27,19 @@ func TestMatchValues(t *testing.T) {
name string
elements []apiextensionsv1.JSON
selector *metav1.LabelSelector
- expected []map[string]any
+ expected []map[string]interface{}
}{
{
name: "no filter",
elements: []apiextensionsv1.JSON{{Raw: []byte(`{"cluster": "cluster","url": "url"}`)}},
selector: &metav1.LabelSelector{},
- expected: []map[string]any{{"cluster": "cluster", "url": "url"}},
+ expected: []map[string]interface{}{{"cluster": "cluster", "url": "url"}},
},
{
name: "nil",
elements: []apiextensionsv1.JSON{{Raw: []byte(`{"cluster": "cluster","url": "url"}`)}},
selector: nil,
- expected: []map[string]any{{"cluster": "cluster", "url": "url"}},
+ expected: []map[string]interface{}{{"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]any{},
+ expected: []map[string]interface{}{},
},
{
name: "values.foo should be bar",
@@ -59,7 +59,7 @@ func TestMatchValues(t *testing.T) {
"values.foo": "bar",
},
},
- expected: []map[string]any{{"cluster": "cluster", "url": "url", "values.foo": "bar"}},
+ expected: []map[string]interface{}{{"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]any
+ expected []map[string]interface{}
}{
{
name: "no filter",
elements: []apiextensionsv1.JSON{{Raw: []byte(`{"cluster": "cluster","url": "url"}`)}},
selector: &metav1.LabelSelector{},
- expected: []map[string]any{{"cluster": "cluster", "url": "url"}},
+ expected: []map[string]interface{}{{"cluster": "cluster", "url": "url"}},
},
{
name: "nil",
elements: []apiextensionsv1.JSON{{Raw: []byte(`{"cluster": "cluster","url": "url"}`)}},
selector: nil,
- expected: []map[string]any{{"cluster": "cluster", "url": "url"}},
+ expected: []map[string]interface{}{{"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]any{},
+ expected: []map[string]interface{}{},
},
{
name: "values.foo should be bar",
@@ -133,7 +133,7 @@ func TestMatchValuesGoTemplate(t *testing.T) {
"values.foo": "bar",
},
},
- expected: []map[string]any{{"cluster": "cluster", "url": "url", "values": map[string]any{"foo": "bar"}}},
+ expected: []map[string]interface{}{{"cluster": "cluster", "url": "url", "values": map[string]interface{}{"foo": "bar"}}},
},
{
name: "values.0 should be bar",
@@ -143,7 +143,7 @@ func TestMatchValuesGoTemplate(t *testing.T) {
"values.0": "bar",
},
},
- expected: []map[string]any{{"cluster": "cluster", "url": "url", "values": []any{"bar"}}},
+ expected: []map[string]interface{}{{"cluster": "cluster", "url": "url", "values": []interface{}{"bar"}}},
},
}
@@ -184,14 +184,14 @@ func TestTransForm(t *testing.T) {
testCases := []struct {
name string
selector *metav1.LabelSelector
- expected []map[string]any
+ expected []map[string]interface{}
}{
{
name: "server filter",
selector: &metav1.LabelSelector{
MatchLabels: map[string]string{"server": "https://production-01.example.com"},
},
- expected: []map[string]any{{
+ expected: []map[string]interface{}{{
"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]any{{
+ expected: []map[string]interface{}{{
"metadata.annotations.foo.argoproj.io": "production",
"metadata.labels.argocd.argoproj.io/secret-type": "cluster",
"metadata.labels.environment": "production",
@@ -342,7 +342,7 @@ func getMockClusterGenerator() Generator {
appClientset := kubefake.NewSimpleClientset(runtimeClusters...)
fakeClient := fake.NewClientBuilder().WithObjects(clusters...).Build()
- return NewClusterGenerator(context.Background(), fakeClient, appClientset, "namespace")
+ return NewClusterGenerator(fakeClient, context.Background(), appClientset, "namespace")
}
func getMockGitGenerator() Generator {
@@ -413,7 +413,7 @@ func TestInterpolateGenerator(t *testing.T) {
},
},
}
- gitGeneratorParams := map[string]any{
+ gitGeneratorParams := map[string]interface{}{
"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]any{
+ clusterGeneratorParams := map[string]interface{}{
"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]any{
- "path": map[string]any{
+ gitGeneratorParams := map[string]interface{}{
+ "path": map[string]interface{}{
"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]any{
+ clusterGeneratorParams := map[string]interface{}{
"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]any
+ params map[string]interface{}
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]any{},
+ params: map[string]interface{}{},
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]any{
+ params: map[string]interface{}{
"name": "in-cluster",
"override": "foo",
},
diff --git a/applicationset/generators/git.go b/applicationset/generators/git.go
index 4afadec31b..d119824f40 100644
--- a/applicationset/generators/git.go
+++ b/applicationset/generators/git.go
@@ -15,10 +15,10 @@ import (
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/yaml"
- "github.com/argoproj/argo-cd/v3/applicationset/services"
- "github.com/argoproj/argo-cd/v3/applicationset/utils"
- argoprojiov1alpha1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- "github.com/argoproj/argo-cd/v3/util/gpg"
+ "github.com/argoproj/argo-cd/v2/applicationset/services"
+ "github.com/argoproj/argo-cd/v2/applicationset/utils"
+ argoprojiov1alpha1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/util/gpg"
)
var _ Generator = (*GitGenerator)(nil)
@@ -28,7 +28,6 @@ type GitGenerator struct {
namespace string
}
-// NewGitGenerator creates a new instance of Git Generator
func NewGitGenerator(repos services.Repos, namespace string) Generator {
g := &GitGenerator{
repos: repos,
@@ -38,17 +37,13 @@ func NewGitGenerator(repos services.Repos, namespace string) Generator {
return g
}
-// GetTemplate returns the ApplicationSetTemplate associated with the Git generator
-// from the provided ApplicationSetGenerator. This template defines how each
-// generated Argo CD Application should be rendered.
func (g *GitGenerator) GetTemplate(appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator) *argoprojiov1alpha1.ApplicationSetTemplate {
return &appSetGenerator.Git.Template
}
-// GetRequeueAfter returns the duration after which the Git generator should be
-// requeued for reconciliation. If RequeueAfterSeconds is set in the generator spec,
-// it uses that value. Otherwise, it falls back to a default requeue interval (3 minutes).
func (g *GitGenerator) GetRequeueAfter(appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator) time.Duration {
+ // Return a requeue default of 3 minutes, if no default is specified.
+
if appSetGenerator.Git.RequeueAfterSeconds != nil {
return time.Duration(*appSetGenerator.Git.RequeueAfterSeconds) * time.Second
}
@@ -56,15 +51,13 @@ func (g *GitGenerator) GetRequeueAfter(appSetGenerator *argoprojiov1alpha1.Appli
return getDefaultRequeueAfter()
}
-// GenerateParams generates a list of parameter maps for the ApplicationSet by evaluating the Git generator's configuration.
-// It supports both directory-based and file-based Git generators.
-func (g *GitGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator, appSet *argoprojiov1alpha1.ApplicationSet, client client.Client) ([]map[string]any, error) {
+func (g *GitGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator, appSet *argoprojiov1alpha1.ApplicationSet, client client.Client) ([]map[string]interface{}, error) {
if appSetGenerator == nil {
- return nil, ErrEmptyAppSetGenerator
+ return nil, EmptyAppSetGeneratorError
}
if appSetGenerator.Git == nil {
- return nil, ErrEmptyAppSetGenerator
+ return nil, EmptyAppSetGeneratorError
}
noRevisionCache := appSet.RefreshRequired()
@@ -74,7 +67,6 @@ func (g *GitGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha1.Applic
// When the project field is templated, the contents of the git repo are required to run the git generator and get the templated value,
// but git generator cannot be called without verifying the commit signature.
// In this case, we skip the signature verification.
- // If the project is templated, we skip the commit verification
if !strings.Contains(appSet.Spec.Template.Spec.Project, "{{") {
project := appSet.Spec.Template.Spec.Project
appProject := &argoprojiov1alpha1.AppProject{}
@@ -89,19 +81,14 @@ func (g *GitGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha1.Applic
verifyCommit = len(appProject.Spec.SignatureKeys) > 0 && gpg.IsGPGEnabled()
}
- // If the project field is templated, we cannot resolve the project name, so we pass an empty string to the repo-server.
- // This means only "globally-scoped" repo credentials can be used for such appsets.
- project := resolveProjectName(appSet.Spec.Template.Spec.Project)
-
var err error
- var res []map[string]any
- switch {
- case len(appSetGenerator.Git.Directories) != 0:
- res, err = g.generateParamsForGitDirectories(appSetGenerator, noRevisionCache, verifyCommit, appSet.Spec.GoTemplate, project, appSet.Spec.GoTemplateOptions)
- case len(appSetGenerator.Git.Files) != 0:
- res, err = g.generateParamsForGitFiles(appSetGenerator, noRevisionCache, verifyCommit, appSet.Spec.GoTemplate, project, appSet.Spec.GoTemplateOptions)
- default:
- return nil, ErrEmptyAppSetGenerator
+ var res []map[string]interface{}
+ 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 {
+ res, err = g.generateParamsForGitFiles(appSetGenerator, noRevisionCache, verifyCommit, appSet.Spec.GoTemplate, appSet.Spec.GoTemplateOptions)
+ } else {
+ return nil, EmptyAppSetGeneratorError
}
if err != nil {
return nil, fmt.Errorf("error generating params from git: %w", err)
@@ -110,11 +97,9 @@ func (g *GitGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha1.Applic
return res, nil
}
-// generateParamsForGitDirectories generates parameters for an ApplicationSet using a directory-based Git generator.
-// It fetches all directories from the given Git repository and revision, optionally using a revision cache and verifying commits.
-// It then filters the directories based on the generator's configuration and renders parameters for the resulting applications
-func (g *GitGenerator) generateParamsForGitDirectories(appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator, noRevisionCache, verifyCommit, useGoTemplate bool, project string, goTemplateOptions []string) ([]map[string]any, error) {
- allPaths, err := g.repos.GetDirectories(context.TODO(), appSetGenerator.Git.RepoURL, appSetGenerator.Git.Revision, project, noRevisionCache, verifyCommit)
+func (g *GitGenerator) generateParamsForGitDirectories(appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator, noRevisionCache, verifyCommit bool, useGoTemplate bool, goTemplateOptions []string) ([]map[string]interface{}, error) {
+ // Directories, not files
+ allPaths, err := g.repos.GetDirectories(context.TODO(), appSetGenerator.Git.RepoURL, appSetGenerator.Git.Revision, noRevisionCache, verifyCommit)
if err != nil {
return nil, fmt.Errorf("error getting directories from repo: %w", err)
}
@@ -137,96 +122,49 @@ func (g *GitGenerator) generateParamsForGitDirectories(appSetGenerator *argoproj
return res, nil
}
-// generateParamsForGitFiles generates parameters for an ApplicationSet using a file-based Git generator.
-// It retrieves and processes specified files from the Git repository, supporting both YAML and JSON formats,
-// and returns a list of parameter maps extracted from the content.
-func (g *GitGenerator) generateParamsForGitFiles(appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator, noRevisionCache, verifyCommit, useGoTemplate bool, project string, goTemplateOptions []string) ([]map[string]any, error) {
- // fileContentMap maps absolute file paths to their byte content
- fileContentMap := make(map[string][]byte)
- var includePatterns []string
- var excludePatterns []string
-
- for _, req := range appSetGenerator.Git.Files {
- if req.Exclude {
- excludePatterns = append(excludePatterns, req.Path)
- } else {
- includePatterns = append(includePatterns, req.Path)
- }
- }
-
- // Fetch all files from include patterns
- for _, includePattern := range includePatterns {
- retrievedFiles, err := g.repos.GetFiles(
- context.TODO(),
- appSetGenerator.Git.RepoURL,
- appSetGenerator.Git.Revision,
- project,
- includePattern,
- noRevisionCache,
- verifyCommit,
- )
+func (g *GitGenerator) generateParamsForGitFiles(appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator, noRevisionCache, verifyCommit bool, useGoTemplate bool, goTemplateOptions []string) ([]map[string]interface{}, error) {
+ // Get all files that match the requested path string, removing duplicates
+ allFiles := make(map[string][]byte)
+ for _, requestedPath := range appSetGenerator.Git.Files {
+ files, err := g.repos.GetFiles(context.TODO(), appSetGenerator.Git.RepoURL, appSetGenerator.Git.Revision, requestedPath.Path, noRevisionCache, verifyCommit)
if err != nil {
return nil, err
}
- for absPath, content := range retrievedFiles {
- fileContentMap[absPath] = content
+ for filePath, content := range files {
+ allFiles[filePath] = content
}
}
- // Now remove files matching any exclude pattern
- for _, excludePattern := range excludePatterns {
- matchingFiles, err := g.repos.GetFiles(
- context.TODO(),
- appSetGenerator.Git.RepoURL,
- appSetGenerator.Git.Revision,
- project,
- excludePattern,
- noRevisionCache,
- verifyCommit,
- )
- if err != nil {
- return nil, err
- }
- for absPath := range matchingFiles {
- // if the file doesn't exist already and you try to delete it from the map
- // the operation is a no-op. It’s safe and doesn't return an error or panic.
- // Hence, we can simply try to delete the file from the path without checking
- // if that file already exists in the map.
- delete(fileContentMap, absPath)
- }
+ // Extract the unduplicated map into a list, and sort by path to ensure a deterministic
+ // processing order in the subsequent step
+ allPaths := []string{}
+ for path := range allFiles {
+ allPaths = append(allPaths, path)
}
+ sort.Strings(allPaths)
- // Get a sorted list of file paths to ensure deterministic processing order
- var filePaths []string
- for path := range fileContentMap {
- filePaths = append(filePaths, path)
- }
- sort.Strings(filePaths)
-
- var allParams []map[string]any
- for _, filePath := range filePaths {
+ // Generate params from each path, and return
+ res := []map[string]interface{}{}
+ for _, path := range allPaths {
// A JSON / YAML file path can contain multiple sets of parameters (ie it is an array)
- paramsFromFileArray, err := g.generateParamsFromGitFile(filePath, fileContentMap[filePath], appSetGenerator.Git.Values, useGoTemplate, goTemplateOptions, appSetGenerator.Git.PathParamPrefix)
+ paramsArray, err := g.generateParamsFromGitFile(path, allFiles[path], appSetGenerator.Git.Values, useGoTemplate, goTemplateOptions, appSetGenerator.Git.PathParamPrefix)
if err != nil {
- return nil, fmt.Errorf("unable to process file '%s': %w", filePath, err)
+ return nil, fmt.Errorf("unable to process file '%s': %w", path, err)
}
- allParams = append(allParams, paramsFromFileArray...)
- }
- return allParams, nil
+ res = append(res, paramsArray...)
+ }
+ return res, nil
}
-// generateParamsFromGitFile parses the content of a Git-tracked file and generates a slice of parameter maps.
-// The file can contain a single YAML/JSON object or an array of such objects. Depending on the useGoTemplate flag,
-// it either preserves structure for Go templating or flattens the objects for use as plain key-value parameters.
-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{}
+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{}{}
// 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]any)
+ singleObj := make(map[string]interface{})
err = yaml.Unmarshal(fileContent, &singleObj)
if err != nil {
return nil, fmt.Errorf("unable to parse file: %w", err)
@@ -234,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]any{})
+ objectsFound = append(objectsFound, map[string]interface{}{})
}
- res := []map[string]any{}
+ res := []map[string]interface{}{}
for _, objectFound := range objectsFound {
- params := map[string]any{}
+ params := map[string]interface{}{}
if useGoTemplate {
for k, v := range objectFound {
params[k] = v
}
- paramPath := map[string]any{}
+ paramPath := map[string]interface{}{}
paramPath["path"] = path.Dir(filePath)
paramPath["basename"] = path.Base(paramPath["path"].(string))
@@ -256,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]any{"path": paramPath}
+ params[pathParamPrefix] = map[string]interface{}{"path": paramPath}
} else {
params["path"] = paramPath
}
@@ -295,10 +233,8 @@ func (g *GitGenerator) generateParamsFromGitFile(filePath string, fileContent []
return res, nil
}
-// filterApps filters the list of all application paths based on inclusion and exclusion rules
-// defined in GitDirectoryGeneratorItems. Each item can either include or exclude matching paths.
func (g *GitGenerator) filterApps(directories []argoprojiov1alpha1.GitDirectoryGeneratorItem, allPaths []string) []string {
- var res []string
+ res := []string{}
for _, appPath := range allPaths {
appInclude := false
appExclude := false
@@ -325,22 +261,19 @@ func (g *GitGenerator) filterApps(directories []argoprojiov1alpha1.GitDirectoryG
return res
}
-// generateParamsFromApps generates a list of parameter maps based on the given app paths.
-// Each app path is converted into a parameter object with path metadata (basename, segments, etc.).
-// It supports both Go templates and flat key-value parameters.
-func (g *GitGenerator) generateParamsFromApps(requestedApps []string, appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator, useGoTemplate bool, goTemplateOptions []string) ([]map[string]any, error) {
- res := make([]map[string]any, len(requestedApps))
+func (g *GitGenerator) generateParamsFromApps(requestedApps []string, appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator, useGoTemplate bool, goTemplateOptions []string) ([]map[string]interface{}, error) {
+ res := make([]map[string]interface{}, len(requestedApps))
for i, a := range requestedApps {
- params := make(map[string]any, 5)
+ params := make(map[string]interface{}, 5)
if useGoTemplate {
- paramPath := map[string]any{}
+ paramPath := map[string]interface{}{}
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]any{"path": paramPath}
+ params[appSetGenerator.Git.PathParamPrefix] = map[string]interface{}{"path": paramPath}
} else {
params["path"] = paramPath
}
@@ -369,12 +302,3 @@ func (g *GitGenerator) generateParamsFromApps(requestedApps []string, appSetGene
return res, nil
}
-
-// resolveProjectName resolves a project name whether templated or not
-func resolveProjectName(project string) string {
- if strings.Contains(project, "{{") {
- return ""
- }
-
- return project
-}
diff --git a/applicationset/generators/git_test.go b/applicationset/generators/git_test.go
index b1b01c9e2a..cd0c14d844 100644
--- a/applicationset/generators/git_test.go
+++ b/applicationset/generators/git_test.go
@@ -1,7 +1,7 @@
package generators
import (
- "errors"
+ "fmt"
"testing"
"github.com/stretchr/testify/assert"
@@ -9,11 +9,11 @@ import (
"github.com/stretchr/testify/require"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
- "k8s.io/utils/ptr"
"sigs.k8s.io/controller-runtime/pkg/client/fake"
- "github.com/argoproj/argo-cd/v3/applicationset/services/mocks"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ "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) {
@@ -32,7 +32,7 @@ foo:
tests := []struct {
name string
args args
- want []map[string]any
+ want []map[string]interface{}
wantErr bool
}{
{
@@ -43,7 +43,7 @@ foo:
values: map[string]string{},
useGoTemplate: false,
},
- want: []map[string]any{
+ want: []map[string]interface{}{
{
"path": "path/dir",
"path.basename": "dir",
@@ -73,7 +73,7 @@ foo:
values: map[string]string{},
useGoTemplate: false,
},
- want: []map[string]any{
+ want: []map[string]interface{}{
{
"foo.bar": "baz",
"path": "path/dir",
@@ -95,7 +95,7 @@ foo:
useGoTemplate: false,
pathParamPrefix: "myRepo",
},
- want: []map[string]any{
+ want: []map[string]interface{}{
{
"foo.bar": "baz",
"myRepo.path": "path/dir",
@@ -116,12 +116,12 @@ foo:
values: map[string]string{},
useGoTemplate: true,
},
- want: []map[string]any{
+ want: []map[string]interface{}{
{
- "foo": map[string]any{
+ "foo": map[string]interface{}{
"bar": "baz",
},
- "path": map[string]any{
+ "path": map[string]interface{}{
"path": "path/dir",
"basename": "dir",
"filename": "file_name.yaml",
@@ -144,13 +144,13 @@ foo:
useGoTemplate: true,
pathParamPrefix: "myRepo",
},
- want: []map[string]any{
+ want: []map[string]interface{}{
{
- "foo": map[string]any{
+ "foo": map[string]interface{}{
"bar": "baz",
},
- "myRepo": map[string]any{
- "path": map[string]any{
+ "myRepo": map[string]interface{}{
+ "path": map[string]interface{}{
"path": "path/dir",
"basename": "dir",
"filename": "file_name.yaml",
@@ -169,12 +169,11 @@ foo:
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
params, err := (*GitGenerator)(nil).generateParamsFromGitFile(tt.args.filePath, tt.args.fileContent, tt.args.values, tt.args.useGoTemplate, tt.args.goTemplateOptions, tt.args.pathParamPrefix)
- if tt.wantErr {
- assert.Error(t, err, "GitGenerator.generateParamsFromGitFile()")
- } else {
- require.NoError(t, err)
- assert.Equal(t, tt.want, params)
+ if (err != nil) != tt.wantErr {
+ t.Errorf("GitGenerator.generateParamsFromGitFile() error = %v, wantErr %v", err, tt.wantErr)
+ return
}
+ assert.Equal(t, tt.want, params)
})
}
}
@@ -182,24 +181,25 @@ foo:
func TestGitGenerateParamsFromDirectories(t *testing.T) {
cases := []struct {
name string
- directories []v1alpha1.GitDirectoryGeneratorItem
+ directories []argoprojiov1alpha1.GitDirectoryGeneratorItem
pathParamPrefix string
repoApps []string
repoError error
values map[string]string
- expected []map[string]any
+ expected []map[string]interface{}
expectedError error
}{
{
name: "happy flow - created apps",
- directories: []v1alpha1.GitDirectoryGeneratorItem{{Path: "*"}},
+ directories: []argoprojiov1alpha1.GitDirectoryGeneratorItem{{Path: "*"}},
repoApps: []string{
"app1",
"app2",
"app_3",
"p1/app4",
},
- expected: []map[string]any{
+ repoError: nil,
+ expected: []map[string]interface{}{
{"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"},
@@ -208,7 +208,7 @@ func TestGitGenerateParamsFromDirectories(t *testing.T) {
},
{
name: "It prefixes path parameters with PathParamPrefix",
- directories: []v1alpha1.GitDirectoryGeneratorItem{{Path: "*"}},
+ directories: []argoprojiov1alpha1.GitDirectoryGeneratorItem{{Path: "*"}},
pathParamPrefix: "myRepo",
repoApps: []string{
"app1",
@@ -217,7 +217,7 @@ func TestGitGenerateParamsFromDirectories(t *testing.T) {
"p1/app4",
},
repoError: nil,
- expected: []map[string]any{
+ expected: []map[string]interface{}{
{"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"},
@@ -226,14 +226,15 @@ func TestGitGenerateParamsFromDirectories(t *testing.T) {
},
{
name: "It filters application according to the paths",
- directories: []v1alpha1.GitDirectoryGeneratorItem{{Path: "p1/*"}, {Path: "p1/*/*"}},
+ directories: []argoprojiov1alpha1.GitDirectoryGeneratorItem{{Path: "p1/*"}, {Path: "p1/*/*"}},
repoApps: []string{
"app1",
"p1/app2",
"p1/p2/app3",
"p1/p2/p3/app4",
},
- expected: []map[string]any{
+ repoError: nil,
+ expected: []map[string]interface{}{
{"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"},
},
@@ -241,7 +242,7 @@ func TestGitGenerateParamsFromDirectories(t *testing.T) {
},
{
name: "It filters application according to the paths with Exclude",
- directories: []v1alpha1.GitDirectoryGeneratorItem{{Path: "p1/*", Exclude: true}, {Path: "*"}, {Path: "*/*"}},
+ directories: []argoprojiov1alpha1.GitDirectoryGeneratorItem{{Path: "p1/*", Exclude: true}, {Path: "*"}, {Path: "*/*"}},
repoApps: []string{
"app1",
"app2",
@@ -250,7 +251,7 @@ func TestGitGenerateParamsFromDirectories(t *testing.T) {
"p2/app3",
},
repoError: nil,
- expected: []map[string]any{
+ expected: []map[string]interface{}{
{"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"},
@@ -259,7 +260,7 @@ func TestGitGenerateParamsFromDirectories(t *testing.T) {
},
{
name: "Expecting same exclude behavior with different order",
- directories: []v1alpha1.GitDirectoryGeneratorItem{{Path: "*"}, {Path: "*/*"}, {Path: "p1/*", Exclude: true}},
+ directories: []argoprojiov1alpha1.GitDirectoryGeneratorItem{{Path: "*"}, {Path: "*/*"}, {Path: "p1/*", Exclude: true}},
repoApps: []string{
"app1",
"app2",
@@ -268,7 +269,7 @@ func TestGitGenerateParamsFromDirectories(t *testing.T) {
"p2/app3",
},
repoError: nil,
- expected: []map[string]any{
+ expected: []map[string]interface{}{
{"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"},
@@ -277,7 +278,7 @@ func TestGitGenerateParamsFromDirectories(t *testing.T) {
},
{
name: "Value variable interpolation",
- directories: []v1alpha1.GitDirectoryGeneratorItem{{Path: "*"}, {Path: "*/*"}},
+ directories: []argoprojiov1alpha1.GitDirectoryGeneratorItem{{Path: "*"}, {Path: "*/*"}},
repoApps: []string{
"app1",
"p1/app2",
@@ -288,7 +289,7 @@ func TestGitGenerateParamsFromDirectories(t *testing.T) {
"aaa": "{{ path[0] }}",
"no-op": "{{ this-does-not-exist }}",
},
- expected: []map[string]any{
+ expected: []map[string]interface{}{
{"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"},
},
@@ -296,19 +297,19 @@ func TestGitGenerateParamsFromDirectories(t *testing.T) {
},
{
name: "handles empty response from repo server",
- directories: []v1alpha1.GitDirectoryGeneratorItem{{Path: "*"}},
+ directories: []argoprojiov1alpha1.GitDirectoryGeneratorItem{{Path: "*"}},
repoApps: []string{},
repoError: nil,
- expected: []map[string]any{},
+ expected: []map[string]interface{}{},
expectedError: nil,
},
{
name: "handles error from repo server",
- directories: []v1alpha1.GitDirectoryGeneratorItem{{Path: "*"}},
+ directories: []argoprojiov1alpha1.GitDirectoryGeneratorItem{{Path: "*"}},
repoApps: []string{},
- repoError: errors.New("error"),
- expected: []map[string]any{},
- expectedError: errors.New("error generating params from git: error getting directories from repo: error"),
+ repoError: fmt.Errorf("error"),
+ expected: []map[string]interface{}{},
+ expectedError: fmt.Errorf("error generating params from git: error getting directories from repo: error"),
},
}
@@ -320,16 +321,16 @@ func TestGitGenerateParamsFromDirectories(t *testing.T) {
argoCDServiceMock := mocks.Repos{}
- argoCDServiceMock.On("GetDirectories", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(testCaseCopy.repoApps, testCaseCopy.repoError)
+ argoCDServiceMock.On("GetDirectories", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(testCaseCopy.repoApps, testCaseCopy.repoError)
gitGenerator := NewGitGenerator(&argoCDServiceMock, "")
- applicationSetInfo := v1alpha1.ApplicationSet{
+ applicationSetInfo := argoprojiov1alpha1.ApplicationSet{
ObjectMeta: metav1.ObjectMeta{
Name: "set",
},
- Spec: v1alpha1.ApplicationSetSpec{
- Generators: []v1alpha1.ApplicationSetGenerator{{
- Git: &v1alpha1.GitGenerator{
+ Spec: argoprojiov1alpha1.ApplicationSetSpec{
+ Generators: []argoprojiov1alpha1.ApplicationSetGenerator{{
+ Git: &argoprojiov1alpha1.GitGenerator{
RepoURL: "RepoURL",
Revision: "Revision",
Directories: testCaseCopy.directories,
@@ -343,7 +344,7 @@ func TestGitGenerateParamsFromDirectories(t *testing.T) {
scheme := runtime.NewScheme()
err := v1alpha1.AddToScheme(scheme)
require.NoError(t, err)
- appProject := v1alpha1.AppProject{}
+ appProject := argoprojiov1alpha1.AppProject{}
client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(&appProject).Build()
@@ -364,16 +365,16 @@ func TestGitGenerateParamsFromDirectories(t *testing.T) {
func TestGitGenerateParamsFromDirectoriesGoTemplate(t *testing.T) {
cases := []struct {
name string
- directories []v1alpha1.GitDirectoryGeneratorItem
+ directories []argoprojiov1alpha1.GitDirectoryGeneratorItem
pathParamPrefix string
repoApps []string
repoError error
- expected []map[string]any
+ expected []map[string]interface{}
expectedError error
}{
{
name: "happy flow - created apps",
- directories: []v1alpha1.GitDirectoryGeneratorItem{{Path: "*"}},
+ directories: []argoprojiov1alpha1.GitDirectoryGeneratorItem{{Path: "*"}},
repoApps: []string{
"app1",
"app2",
@@ -381,9 +382,9 @@ func TestGitGenerateParamsFromDirectoriesGoTemplate(t *testing.T) {
"p1/app4",
},
repoError: nil,
- expected: []map[string]any{
+ expected: []map[string]interface{}{
{
- "path": map[string]any{
+ "path": map[string]interface{}{
"path": "app1",
"basename": "app1",
"basenameNormalized": "app1",
@@ -393,7 +394,7 @@ func TestGitGenerateParamsFromDirectoriesGoTemplate(t *testing.T) {
},
},
{
- "path": map[string]any{
+ "path": map[string]interface{}{
"path": "app2",
"basename": "app2",
"basenameNormalized": "app2",
@@ -403,7 +404,7 @@ func TestGitGenerateParamsFromDirectoriesGoTemplate(t *testing.T) {
},
},
{
- "path": map[string]any{
+ "path": map[string]interface{}{
"path": "app_3",
"basename": "app_3",
"basenameNormalized": "app-3",
@@ -417,7 +418,7 @@ func TestGitGenerateParamsFromDirectoriesGoTemplate(t *testing.T) {
},
{
name: "It prefixes path parameters with PathParamPrefix",
- directories: []v1alpha1.GitDirectoryGeneratorItem{{Path: "*"}},
+ directories: []argoprojiov1alpha1.GitDirectoryGeneratorItem{{Path: "*"}},
pathParamPrefix: "myRepo",
repoApps: []string{
"app1",
@@ -426,10 +427,10 @@ func TestGitGenerateParamsFromDirectoriesGoTemplate(t *testing.T) {
"p1/app4",
},
repoError: nil,
- expected: []map[string]any{
+ expected: []map[string]interface{}{
{
- "myRepo": map[string]any{
- "path": map[string]any{
+ "myRepo": map[string]interface{}{
+ "path": map[string]interface{}{
"path": "app1",
"basename": "app1",
"basenameNormalized": "app1",
@@ -440,8 +441,8 @@ func TestGitGenerateParamsFromDirectoriesGoTemplate(t *testing.T) {
},
},
{
- "myRepo": map[string]any{
- "path": map[string]any{
+ "myRepo": map[string]interface{}{
+ "path": map[string]interface{}{
"path": "app2",
"basename": "app2",
"basenameNormalized": "app2",
@@ -452,8 +453,8 @@ func TestGitGenerateParamsFromDirectoriesGoTemplate(t *testing.T) {
},
},
{
- "myRepo": map[string]any{
- "path": map[string]any{
+ "myRepo": map[string]interface{}{
+ "path": map[string]interface{}{
"path": "app_3",
"basename": "app_3",
"basenameNormalized": "app-3",
@@ -468,7 +469,7 @@ func TestGitGenerateParamsFromDirectoriesGoTemplate(t *testing.T) {
},
{
name: "It filters application according to the paths",
- directories: []v1alpha1.GitDirectoryGeneratorItem{{Path: "p1/*"}, {Path: "p1/*/*"}},
+ directories: []argoprojiov1alpha1.GitDirectoryGeneratorItem{{Path: "p1/*"}, {Path: "p1/*/*"}},
repoApps: []string{
"app1",
"p1/app2",
@@ -476,9 +477,9 @@ func TestGitGenerateParamsFromDirectoriesGoTemplate(t *testing.T) {
"p1/p2/p3/app4",
},
repoError: nil,
- expected: []map[string]any{
+ expected: []map[string]interface{}{
{
- "path": map[string]any{
+ "path": map[string]interface{}{
"path": "p1/app2",
"basename": "app2",
"basenameNormalized": "app2",
@@ -489,7 +490,7 @@ func TestGitGenerateParamsFromDirectoriesGoTemplate(t *testing.T) {
},
},
{
- "path": map[string]any{
+ "path": map[string]interface{}{
"path": "p1/p2/app3",
"basename": "app3",
"basenameNormalized": "app3",
@@ -505,7 +506,7 @@ func TestGitGenerateParamsFromDirectoriesGoTemplate(t *testing.T) {
},
{
name: "It filters application according to the paths with Exclude",
- directories: []v1alpha1.GitDirectoryGeneratorItem{{Path: "p1/*", Exclude: true}, {Path: "*"}, {Path: "*/*"}},
+ directories: []argoprojiov1alpha1.GitDirectoryGeneratorItem{{Path: "p1/*", Exclude: true}, {Path: "*"}, {Path: "*/*"}},
repoApps: []string{
"app1",
"app2",
@@ -514,9 +515,9 @@ func TestGitGenerateParamsFromDirectoriesGoTemplate(t *testing.T) {
"p2/app3",
},
repoError: nil,
- expected: []map[string]any{
+ expected: []map[string]interface{}{
{
- "path": map[string]any{
+ "path": map[string]interface{}{
"path": "app1",
"basename": "app1",
"basenameNormalized": "app1",
@@ -526,7 +527,7 @@ func TestGitGenerateParamsFromDirectoriesGoTemplate(t *testing.T) {
},
},
{
- "path": map[string]any{
+ "path": map[string]interface{}{
"path": "app2",
"basename": "app2",
"basenameNormalized": "app2",
@@ -536,7 +537,7 @@ func TestGitGenerateParamsFromDirectoriesGoTemplate(t *testing.T) {
},
},
{
- "path": map[string]any{
+ "path": map[string]interface{}{
"path": "p2/app3",
"basename": "app3",
"basenameNormalized": "app3",
@@ -551,7 +552,7 @@ func TestGitGenerateParamsFromDirectoriesGoTemplate(t *testing.T) {
},
{
name: "Expecting same exclude behavior with different order",
- directories: []v1alpha1.GitDirectoryGeneratorItem{{Path: "*"}, {Path: "*/*"}, {Path: "p1/*", Exclude: true}},
+ directories: []argoprojiov1alpha1.GitDirectoryGeneratorItem{{Path: "*"}, {Path: "*/*"}, {Path: "p1/*", Exclude: true}},
repoApps: []string{
"app1",
"app2",
@@ -560,9 +561,9 @@ func TestGitGenerateParamsFromDirectoriesGoTemplate(t *testing.T) {
"p2/app3",
},
repoError: nil,
- expected: []map[string]any{
+ expected: []map[string]interface{}{
{
- "path": map[string]any{
+ "path": map[string]interface{}{
"path": "app1",
"basename": "app1",
"basenameNormalized": "app1",
@@ -572,7 +573,7 @@ func TestGitGenerateParamsFromDirectoriesGoTemplate(t *testing.T) {
},
},
{
- "path": map[string]any{
+ "path": map[string]interface{}{
"path": "app2",
"basename": "app2",
"basenameNormalized": "app2",
@@ -582,7 +583,7 @@ func TestGitGenerateParamsFromDirectoriesGoTemplate(t *testing.T) {
},
},
{
- "path": map[string]any{
+ "path": map[string]interface{}{
"path": "p2/app3",
"basename": "app3",
"basenameNormalized": "app3",
@@ -597,19 +598,19 @@ func TestGitGenerateParamsFromDirectoriesGoTemplate(t *testing.T) {
},
{
name: "handles empty response from repo server",
- directories: []v1alpha1.GitDirectoryGeneratorItem{{Path: "*"}},
+ directories: []argoprojiov1alpha1.GitDirectoryGeneratorItem{{Path: "*"}},
repoApps: []string{},
repoError: nil,
- expected: []map[string]any{},
+ expected: []map[string]interface{}{},
expectedError: nil,
},
{
name: "handles error from repo server",
- directories: []v1alpha1.GitDirectoryGeneratorItem{{Path: "*"}},
+ directories: []argoprojiov1alpha1.GitDirectoryGeneratorItem{{Path: "*"}},
repoApps: []string{},
- repoError: errors.New("error"),
- expected: []map[string]any{},
- expectedError: errors.New("error generating params from git: error getting directories from repo: error"),
+ repoError: fmt.Errorf("error"),
+ expected: []map[string]interface{}{},
+ expectedError: fmt.Errorf("error generating params from git: error getting directories from repo: error"),
},
}
@@ -621,17 +622,17 @@ func TestGitGenerateParamsFromDirectoriesGoTemplate(t *testing.T) {
argoCDServiceMock := mocks.Repos{}
- argoCDServiceMock.On("GetDirectories", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(testCaseCopy.repoApps, testCaseCopy.repoError)
+ argoCDServiceMock.On("GetDirectories", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(testCaseCopy.repoApps, testCaseCopy.repoError)
gitGenerator := NewGitGenerator(&argoCDServiceMock, "")
- applicationSetInfo := v1alpha1.ApplicationSet{
+ applicationSetInfo := argoprojiov1alpha1.ApplicationSet{
ObjectMeta: metav1.ObjectMeta{
Name: "set",
},
- Spec: v1alpha1.ApplicationSetSpec{
+ Spec: argoprojiov1alpha1.ApplicationSetSpec{
GoTemplate: true,
- Generators: []v1alpha1.ApplicationSetGenerator{{
- Git: &v1alpha1.GitGenerator{
+ Generators: []argoprojiov1alpha1.ApplicationSetGenerator{{
+ Git: &argoprojiov1alpha1.GitGenerator{
RepoURL: "RepoURL",
Revision: "Revision",
Directories: testCaseCopy.directories,
@@ -644,7 +645,7 @@ func TestGitGenerateParamsFromDirectoriesGoTemplate(t *testing.T) {
scheme := runtime.NewScheme()
err := v1alpha1.AddToScheme(scheme)
require.NoError(t, err)
- appProject := v1alpha1.AppProject{}
+ appProject := argoprojiov1alpha1.AppProject{}
client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(&appProject).Build()
@@ -666,18 +667,18 @@ func TestGitGenerateParamsFromFiles(t *testing.T) {
cases := []struct {
name string
// files is the list of paths/globs to match
- files []v1alpha1.GitFileGeneratorItem
+ files []argoprojiov1alpha1.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
repoPathsError error
values map[string]string
- expected []map[string]any
+ expected []map[string]interface{}
expectedError error
}{
{
name: "happy flow: create params from git files",
- files: []v1alpha1.GitFileGeneratorItem{{Path: "**/config.json"}},
+ files: []argoprojiov1alpha1.GitFileGeneratorItem{{Path: "**/config.json"}},
repoFileContents: map[string][]byte{
"cluster-config/production/config.json": []byte(`{
"cluster": {
@@ -703,7 +704,7 @@ func TestGitGenerateParamsFromFiles(t *testing.T) {
}`),
},
repoPathsError: nil,
- expected: []map[string]any{
+ expected: []map[string]interface{}{
{
"cluster.owner": "john.doe@example.com",
"cluster.name": "production",
@@ -737,7 +738,7 @@ func TestGitGenerateParamsFromFiles(t *testing.T) {
},
{
name: "Value variable interpolation",
- files: []v1alpha1.GitFileGeneratorItem{{Path: "**/config.json"}},
+ files: []argoprojiov1alpha1.GitFileGeneratorItem{{Path: "**/config.json"}},
repoFileContents: map[string][]byte{
"cluster-config/production/config.json": []byte(`{
"cluster": {
@@ -767,7 +768,7 @@ func TestGitGenerateParamsFromFiles(t *testing.T) {
"aaa": "{{ cluster.owner }}",
"no-op": "{{ this-does-not-exist }}",
},
- expected: []map[string]any{
+ expected: []map[string]interface{}{
{
"cluster.owner": "john.doe@example.com",
"cluster.name": "production",
@@ -805,25 +806,25 @@ func TestGitGenerateParamsFromFiles(t *testing.T) {
},
{
name: "handles error during getting repo paths",
- files: []v1alpha1.GitFileGeneratorItem{{Path: "**/config.json"}},
+ files: []argoprojiov1alpha1.GitFileGeneratorItem{{Path: "**/config.json"}},
repoFileContents: map[string][]byte{},
- repoPathsError: errors.New("paths error"),
- expected: []map[string]any{},
- expectedError: errors.New("error generating params from git: paths error"),
+ repoPathsError: fmt.Errorf("paths error"),
+ expected: []map[string]interface{}{},
+ expectedError: fmt.Errorf("error generating params from git: paths error"),
},
{
name: "test invalid JSON file returns error",
- files: []v1alpha1.GitFileGeneratorItem{{Path: "**/config.json"}},
+ files: []argoprojiov1alpha1.GitFileGeneratorItem{{Path: "**/config.json"}},
repoFileContents: map[string][]byte{
"cluster-config/production/config.json": []byte(`invalid json file`),
},
repoPathsError: nil,
- 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 {}"),
+ expected: []map[string]interface{}{},
+ expectedError: fmt.Errorf("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 {}"),
},
{
name: "test JSON array",
- files: []v1alpha1.GitFileGeneratorItem{{Path: "**/config.json"}},
+ files: []argoprojiov1alpha1.GitFileGeneratorItem{{Path: "**/config.json"}},
repoFileContents: map[string][]byte{
"cluster-config/production/config.json": []byte(`
[
@@ -847,7 +848,7 @@ func TestGitGenerateParamsFromFiles(t *testing.T) {
]`),
},
repoPathsError: nil,
- expected: []map[string]any{
+ expected: []map[string]interface{}{
{
"cluster.owner": "john.doe@example.com",
"cluster.name": "production",
@@ -878,7 +879,7 @@ func TestGitGenerateParamsFromFiles(t *testing.T) {
},
{
name: "Test YAML flow",
- files: []v1alpha1.GitFileGeneratorItem{{Path: "**/config.yaml"}},
+ files: []argoprojiov1alpha1.GitFileGeneratorItem{{Path: "**/config.yaml"}},
repoFileContents: map[string][]byte{
"cluster-config/production/config.yaml": []byte(`
cluster:
@@ -899,7 +900,7 @@ cluster:
`),
},
repoPathsError: nil,
- expected: []map[string]any{
+ expected: []map[string]interface{}{
{
"cluster.owner": "john.doe@example.com",
"cluster.name": "production",
@@ -932,7 +933,7 @@ cluster:
},
{
name: "test YAML array",
- files: []v1alpha1.GitFileGeneratorItem{{Path: "**/config.yaml"}},
+ files: []argoprojiov1alpha1.GitFileGeneratorItem{{Path: "**/config.yaml"}},
repoFileContents: map[string][]byte{
"cluster-config/production/config.yaml": []byte(`
- cluster:
@@ -947,7 +948,7 @@ cluster:
address: https://kubernetes.default.svc`),
},
repoPathsError: nil,
- expected: []map[string]any{
+ expected: []map[string]interface{}{
{
"cluster.owner": "john.doe@example.com",
"cluster.name": "production",
@@ -985,17 +986,17 @@ cluster:
t.Parallel()
argoCDServiceMock := mocks.Repos{}
- argoCDServiceMock.On("GetFiles", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).
+ argoCDServiceMock.On("GetFiles", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).
Return(testCaseCopy.repoFileContents, testCaseCopy.repoPathsError)
gitGenerator := NewGitGenerator(&argoCDServiceMock, "")
- applicationSetInfo := v1alpha1.ApplicationSet{
+ applicationSetInfo := argoprojiov1alpha1.ApplicationSet{
ObjectMeta: metav1.ObjectMeta{
Name: "set",
},
- Spec: v1alpha1.ApplicationSetSpec{
- Generators: []v1alpha1.ApplicationSetGenerator{{
- Git: &v1alpha1.GitGenerator{
+ Spec: argoprojiov1alpha1.ApplicationSetSpec{
+ Generators: []argoprojiov1alpha1.ApplicationSetGenerator{{
+ Git: &argoprojiov1alpha1.GitGenerator{
RepoURL: "RepoURL",
Revision: "Revision",
Files: testCaseCopy.files,
@@ -1008,927 +1009,12 @@ cluster:
scheme := runtime.NewScheme()
err := v1alpha1.AddToScheme(scheme)
require.NoError(t, err)
- appProject := v1alpha1.AppProject{}
-
- client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(&appProject).Build()
-
- got, err := gitGenerator.GenerateParams(&applicationSetInfo.Spec.Generators[0], &applicationSetInfo, client)
-
- if testCaseCopy.expectedError != nil {
- require.EqualError(t, err, testCaseCopy.expectedError.Error())
- } else {
- require.NoError(t, err)
- assert.ElementsMatch(t, testCaseCopy.expected, got)
- }
-
- argoCDServiceMock.AssertExpectations(t)
- })
- }
-}
-
-// TestGitGeneratorParamsFromFilesWithExcludeOptionWithNewGlobbing tests the params values generated by git file generator
-// when exclude option is set to true. It gives the result files based on new globbing pattern - doublestar package
-func TestGitGeneratorParamsFromFilesWithExcludeOptionWithNewGlobbing(t *testing.T) {
- cases := []struct {
- name string
- // files is the list of paths/globs to match
- files []v1alpha1.GitFileGeneratorItem
- // includePattern contains a list of file patterns that needs to be included
- includePattern []string
- // excludePattern contains a list of file patterns that needs to be excluded
- excludePattern []string
- // includeFiles is a map with key as absolute path to file and value as the content in bytes that satisfies the includePattern
- includeFiles map[string][]byte
- // excludeFiles is a map with key as absolute path to file and value as the content in bytes that satisfies the excludePattern
- // This means all the files should be excluded
- excludeFiles map[string][]byte
- // noMatchFiles contains all the files that neither match include pattern nor exclude pattern
- // Instead of keeping those files in the excludeFiles map, it is better to keep those files separately
- // in a separate field like 'noMatchFiles' to avoid confusion.
- noMatchFiles map[string][]byte
- // if repoPathsError is non-nil, the call to GetPaths(...) will return this error value
- repoPathsError error
- values map[string]string
- expected []map[string]any
- expectedError error
- }{
- {
- name: "filter files according to file-path with exclude",
- files: []v1alpha1.GitFileGeneratorItem{
- {
- Path: "**/config.json",
- },
- {
- Path: "p1/**/config.json",
- Exclude: true,
- },
- },
- includePattern: []string{"**/config.json"},
- excludePattern: []string{"p1/**/config.json"},
- includeFiles: map[string][]byte{
- "cluster-config/production/config.json": []byte(`{
- "cluster": {
- "owner": "john.doe@example.com",
- "name": "production",
- "address": "https://kubernetes.default.svc"
- },
- "key1": "val1",
- "key2": {
- "key2_1": "val2_1",
- "key2_2": {
- "key2_2_1": "val2_2_1"
- }
- },
- "key3": 123
- }
-`),
- "p1/config.json": []byte(`{
- "database": {
- "admin": "db.admin@example.com",
- "name": "user-data",
- "host": "db.internal.local",
- "settings": {
- "replicas": 3,
- "backup": "daily"
- }
- }
- }
-`),
- "p1/p2/config.json": []byte(``),
- },
- excludeFiles: map[string][]byte{
- "p1/config.json": []byte(`{
- "database": {
- "admin": "db.admin@example.com",
- "name": "user-data",
- "host": "db.internal.local",
- "settings": {
- "replicas": 3,
- "backup": "daily"
- }
- }
- }
-`),
- "p1/p2/config.json": []byte(``),
- },
- repoPathsError: nil,
- expected: []map[string]any{
- {
- "cluster.owner": "john.doe@example.com",
- "cluster.name": "production",
- "cluster.address": "https://kubernetes.default.svc",
- "key1": "val1",
- "key2.key2_1": "val2_1",
- "key2.key2_2.key2_2_1": "val2_2_1",
- "key3": "123",
- "path": "cluster-config/production",
- "path.basename": "production",
- "path[0]": "cluster-config",
- "path[1]": "production",
- "path.basenameNormalized": "production",
- "path.filename": "config.json",
- "path.filenameNormalized": "config.json",
- },
- },
- },
- {
- name: "filter files according to multiple file-paths with exclude",
- files: []v1alpha1.GitFileGeneratorItem{
- {Path: "**/config.json"},
- {Path: "p1/app2/config.json", Exclude: true},
- {Path: "p1/app3/config.json", Exclude: true},
- },
- includePattern: []string{"**/config.json"},
- excludePattern: []string{"p1/app2/config.json", "p1/app3/config.json"},
- includeFiles: map[string][]byte{
- "p1/config.json": []byte(`{
- "cluster": {
- "owner": "john.doe@example.com",
- "name": "production",
- "address": "https://kubernetes.default.svc",
- "inner": {
- "one" : "two"
- }
- }
-}`),
- "p1/app2/config.json": []byte(`{}`),
- "p1/app3/config.json": []byte(`{}`),
- },
- excludeFiles: map[string][]byte{
- "p1/app2/config.json": []byte(`{}`),
- "p1/app3/config.json": []byte(`{}`),
- },
- repoPathsError: nil,
- expected: []map[string]any{
- {
- "cluster.owner": "john.doe@example.com",
- "cluster.name": "production",
- "cluster.address": "https://kubernetes.default.svc",
- "cluster.inner.one": "two",
- "path": "p1",
- "path.basename": "p1",
- "path[0]": "p1",
- "path.basenameNormalized": "p1",
- "path.filename": "config.json",
- "path.filenameNormalized": "config.json",
- },
- },
- },
- {
- name: "docs example test case to filter files according to multiple file-paths with exclude",
- files: []v1alpha1.GitFileGeneratorItem{{Path: "cluster-config/**/config.json"}, {Path: "cluster-config/*/dev/config.json", Exclude: true}},
- includePattern: []string{"cluster-config/**/config.json"},
- excludePattern: []string{"cluster-config/*/dev/config.json"},
- includeFiles: map[string][]byte{
- "cluster-config/engineering/prod/config.json": []byte(`
-cluster:
- owner: john.doe@example.com
- name: production
- address: https://kubernetes.default.svc
-`),
- "cluster-config/engineering/dev/config.json": []byte(`
-cluster:
- owner: foo.bar@example.com
- name: staging
- address: https://kubernetes.default.svc
-`),
- },
- excludeFiles: map[string][]byte{
- "cluster-config/engineering/dev/config.json": []byte(`
-cluster:
- owner: foo.bar@example.com
- name: staging
- address: https://kubernetes.default.svc
-`),
- },
- repoPathsError: nil,
- expected: []map[string]any{
- {
- "cluster.owner": "john.doe@example.com",
- "cluster.name": "production",
- "cluster.address": "https://kubernetes.default.svc",
- "path": "cluster-config/engineering/prod",
- "path.basename": "prod",
- "path[0]": "cluster-config",
- "path[1]": "engineering",
- "path[2]": "prod",
- "path.basenameNormalized": "prod",
- "path.filename": "config.json",
- "path.filenameNormalized": "config.json",
- },
- },
- },
- {
- name: "testcase to verify new globbing pattern without any exclude",
- files: []v1alpha1.GitFileGeneratorItem{{Path: "some-path/*.yaml"}},
- includePattern: []string{"some-path/*.yaml"},
- excludePattern: nil,
- includeFiles: map[string][]byte{
- "some-path/values.yaml": []byte(`
-cluster:
- owner: john.doe@example.com
- name: production
- address: https://kubernetes.default.svc
-`),
- },
- excludeFiles: map[string][]byte{},
- noMatchFiles: map[string][]byte{
- "some-path/staging/values.yaml": []byte(`
-cluster:
- owner: foo.bar@example.com
- name: staging
- address: https://kubernetes.default.svc
-`),
- },
- repoPathsError: nil,
- expected: []map[string]any{
- {
- "cluster.owner": "john.doe@example.com",
- "cluster.name": "production",
- "cluster.address": "https://kubernetes.default.svc",
- "path": "some-path",
- "path.basename": "some-path",
- "path[0]": "some-path",
- "path.basenameNormalized": "some-path",
- "path.filename": "values.yaml",
- "path.filenameNormalized": "values.yaml",
- },
- },
- expectedError: nil,
- },
- {
- name: "test to verify the solution for Git File Generator Problem", // https://github.com/argoproj/argo-cd/blob/master/docs/operator-manual/applicationset/Generators-Git-File-Globbing.md#git-file-generator-globbing
- files: []v1alpha1.GitFileGeneratorItem{{Path: "cluster-charts/*/*/values.yaml"}, {Path: "cluster-charts/*/values.yaml", Exclude: true}},
- includePattern: []string{"cluster-charts/*/*/values.yaml"},
- excludePattern: []string{"cluster-charts/*/values.yaml"},
- includeFiles: map[string][]byte{
- "cluster-charts/cluster1/mychart/values.yaml": []byte(`
-env: staging
-`),
- "cluster-charts/cluster1/myotherchart/values.yaml": []byte(`
-env: prod
-`),
- },
- excludeFiles: map[string][]byte{
- "cluster-charts/cluster2/values.yaml": []byte(`
-env: dev
-`),
- },
- noMatchFiles: map[string][]byte{
- "cluster-charts/cluster1/mychart/charts/mysubchart/values.yaml": []byte(`
-env: testing
-`),
- },
- repoPathsError: nil,
- expected: []map[string]any{
- {
- "env": "staging",
- "path": "cluster-charts/cluster1/mychart",
- "path.filenameNormalized": "values.yaml",
- "path[0]": "cluster-charts",
- "path[1]": "cluster1",
- "path[2]": "mychart",
- "path.basename": "mychart",
- "path.filename": "values.yaml",
- "path.basenameNormalized": "mychart",
- },
- {
- "env": "prod",
- "path": "cluster-charts/cluster1/myotherchart",
- "path.filenameNormalized": "values.yaml",
- "path[0]": "cluster-charts",
- "path[1]": "cluster1",
- "path[2]": "myotherchart",
- "path.basename": "myotherchart",
- "path.filename": "values.yaml",
- "path.basenameNormalized": "myotherchart",
- },
- },
- expectedError: nil,
- },
- }
- for _, testCase := range cases {
- testCaseCopy := testCase
-
- t.Run(testCaseCopy.name, func(t *testing.T) {
- t.Parallel()
-
- argoCDServiceMock := mocks.Repos{}
-
- // IMPORTANT: we try to get the files from the repo server that matches the patterns
- // If we find those files also satisfy the exclude pattern, we remove them from map
- // This is generally done by the g.repos.GetFiles() function.
- // With the below mock setup, we make sure that if the GetFiles() function gets called
- // for a include or exclude pattern, it should always return the includeFiles or excludeFiles.
- for _, pattern := range testCaseCopy.excludePattern {
- argoCDServiceMock.
- On("GetFiles", mock.Anything, mock.Anything, mock.Anything, mock.Anything, pattern, mock.Anything, mock.Anything).
- Return(testCaseCopy.excludeFiles, testCaseCopy.repoPathsError)
- }
-
- for _, pattern := range testCaseCopy.includePattern {
- argoCDServiceMock.
- On("GetFiles", mock.Anything, mock.Anything, mock.Anything, mock.Anything, pattern, mock.Anything, mock.Anything).
- Return(testCaseCopy.includeFiles, testCaseCopy.repoPathsError)
- }
-
- gitGenerator := NewGitGenerator(&argoCDServiceMock, "")
- applicationSetInfo := v1alpha1.ApplicationSet{
- ObjectMeta: metav1.ObjectMeta{
- Name: "set",
- },
- Spec: v1alpha1.ApplicationSetSpec{
- Generators: []v1alpha1.ApplicationSetGenerator{{
- Git: &v1alpha1.GitGenerator{
- RepoURL: "RepoURL",
- Revision: "Revision",
- Files: testCaseCopy.files,
- Values: testCaseCopy.values,
- },
- }},
- },
- }
-
- scheme := runtime.NewScheme()
- err := v1alpha1.AddToScheme(scheme)
- require.NoError(t, err)
- appProject := v1alpha1.AppProject{}
-
- client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(&appProject).Build()
-
- got, err := gitGenerator.GenerateParams(&applicationSetInfo.Spec.Generators[0], &applicationSetInfo, client)
-
- if testCaseCopy.expectedError != nil {
- require.EqualError(t, err, testCaseCopy.expectedError.Error())
- } else {
- require.NoError(t, err)
- assert.ElementsMatch(t, testCaseCopy.expected, got)
- }
-
- argoCDServiceMock.AssertExpectations(t)
- })
- }
-}
-
-// TestGitGeneratorParamsFromFilesWithExcludeOptionWithOldGlobbing tests the params values generated by git file generator
-// // when exclude option is set to true. It gives the result files based on old globbing pattern - git ls-files
-func TestGitGeneratorParamsFromFilesWithExcludeOptionWithOldGlobbing(t *testing.T) {
- cases := []struct {
- name string
- // files is the list of paths/globs to match
- files []v1alpha1.GitFileGeneratorItem
- // includePattern contains a list of file patterns that needs to be included
- includePattern []string
- // excludePattern contains a list of file patterns that needs to be excluded
- excludePattern []string
- // includeFiles is a map with key as absolute path to file and value as the content in bytes that satisfies the includePattern
- includeFiles map[string][]byte
- // excludeFiles is a map with key as absolute path to file and value as the content in bytes that satisfies the excludePattern
- // This means all the files should be excluded
- excludeFiles map[string][]byte
- // noMatchFiles contains all the files that neither match include pattern nor exclude pattern
- // Instead of keeping those files in the excludeFiles map, it is better to keep those files separately
- // in a separate field like 'noMatchFiles' to avoid confusion.
- noMatchFiles map[string][]byte
- // if repoPathsError is non-nil, the call to GetPaths(...) will return this error value
- repoPathsError error
- values map[string]string
- expected []map[string]any
- expectedError error
- }{
- {
- name: "filter files according to file-path with exclude",
- files: []v1alpha1.GitFileGeneratorItem{
- {
- Path: "**/config.json",
- },
- {
- Path: "p1/**/config.json",
- Exclude: true,
- },
- },
- includePattern: []string{"**/config.json"},
- excludePattern: []string{"p1/**/config.json"},
- includeFiles: map[string][]byte{
- "cluster-config/production/config.json": []byte(`{
- "cluster": {
- "owner": "john.doe@example.com",
- "name": "production",
- "address": "https://kubernetes.default.svc"
- },
- "key1": "val1",
- "key2": {
- "key2_1": "val2_1",
- "key2_2": {
- "key2_2_1": "val2_2_1"
- }
- },
- "key3": 123
- }
-`),
- "p1/config.json": []byte(`{
- "database": {
- "admin": "db.admin@example.com",
- "name": "user-data",
- "host": "db.internal.local",
- "settings": {
- "replicas": 3,
- "backup": "daily"
- }
- }
- }
-`),
- "p1/p2/config.json": []byte(``),
- },
- excludeFiles: map[string][]byte{
- "p1/config.json": []byte(`{
- "database": {
- "admin": "db.admin@example.com",
- "name": "user-data",
- "host": "db.internal.local",
- "settings": {
- "replicas": 3,
- "backup": "daily"
- }
- }
- }
-`),
- "p1/p2/config.json": []byte(``),
- },
- repoPathsError: nil,
- expected: []map[string]any{
- {
- "cluster.owner": "john.doe@example.com",
- "cluster.name": "production",
- "cluster.address": "https://kubernetes.default.svc",
- "key1": "val1",
- "key2.key2_1": "val2_1",
- "key2.key2_2.key2_2_1": "val2_2_1",
- "key3": "123",
- "path": "cluster-config/production",
- "path.basename": "production",
- "path[0]": "cluster-config",
- "path[1]": "production",
- "path.basenameNormalized": "production",
- "path.filename": "config.json",
- "path.filenameNormalized": "config.json",
- },
- },
- },
- {
- name: "filter files according to multiple file-paths with exclude",
- files: []v1alpha1.GitFileGeneratorItem{
- {Path: "**/config.json"},
- {Path: "p1/app2/config.json", Exclude: true},
- {Path: "p1/app3/config.json", Exclude: true},
- },
- includePattern: []string{"**/config.json"},
- excludePattern: []string{"p1/app2/config.json", "p1/app3/config.json"},
- includeFiles: map[string][]byte{
- "p1/config.json": []byte(`{
- "cluster": {
- "owner": "john.doe@example.com",
- "name": "production",
- "address": "https://kubernetes.default.svc",
- "inner": {
- "one" : "two"
- }
- }
-}`),
- "p1/app2/config.json": []byte(`{}`),
- "p1/app3/config.json": []byte(`{}`),
- },
- excludeFiles: map[string][]byte{
- "p1/app2/config.json": []byte(`{}`),
- "p1/app3/config.json": []byte(`{}`),
- },
- repoPathsError: nil,
- expected: []map[string]any{
- {
- "cluster.owner": "john.doe@example.com",
- "cluster.name": "production",
- "cluster.address": "https://kubernetes.default.svc",
- "cluster.inner.one": "two",
- "path": "p1",
- "path.basename": "p1",
- "path[0]": "p1",
- "path.basenameNormalized": "p1",
- "path.filename": "config.json",
- "path.filenameNormalized": "config.json",
- },
- },
- },
- {
- name: "docs example test case to filter files according to multiple file-paths with exclude",
- files: []v1alpha1.GitFileGeneratorItem{{Path: "cluster-config/**/config.json"}, {Path: "cluster-config/*/dev/config.json", Exclude: true}},
- includePattern: []string{"cluster-config/**/config.json"},
- excludePattern: []string{"cluster-config/*/dev/config.json"},
- includeFiles: map[string][]byte{
- "cluster-config/engineering/prod/config.json": []byte(`
-cluster:
- owner: john.doe@example.com
- name: production
- address: https://kubernetes.default.svc
-`),
- "cluster-config/engineering/dev/config.json": []byte(`
-cluster:
- owner: foo.bar@example.com
- name: staging
- address: https://kubernetes.default.svc
-`),
- },
- excludeFiles: map[string][]byte{
- "cluster-config/engineering/dev/config.json": []byte(`
-cluster:
- owner: foo.bar@example.com
- name: staging
- address: https://kubernetes.default.svc
-`),
- },
- repoPathsError: nil,
- expected: []map[string]any{
- {
- "cluster.owner": "john.doe@example.com",
- "cluster.name": "production",
- "cluster.address": "https://kubernetes.default.svc",
- "path": "cluster-config/engineering/prod",
- "path.basename": "prod",
- "path[0]": "cluster-config",
- "path[1]": "engineering",
- "path[2]": "prod",
- "path.basenameNormalized": "prod",
- "path.filename": "config.json",
- "path.filenameNormalized": "config.json",
- },
- },
- },
- {
- name: "testcase to verify new globbing pattern without any exclude",
- files: []v1alpha1.GitFileGeneratorItem{{Path: "some-path/*.yaml"}},
- includePattern: []string{"some-path/*.yaml"},
- excludePattern: nil,
- includeFiles: map[string][]byte{
- "some-path/values.yaml": []byte(`
-cluster:
- owner: john.doe@example.com
- name: production
- address: https://kubernetes.default.svc
-`),
- "some-path/staging/values.yaml": []byte(`
-cluster:
- owner: foo.bar@example.com
- name: staging
- address: https://kubernetes.default.svc
-`),
- },
- excludeFiles: map[string][]byte{},
- repoPathsError: nil,
- expected: []map[string]any{
- {
- "cluster.owner": "john.doe@example.com",
- "cluster.name": "production",
- "cluster.address": "https://kubernetes.default.svc",
- "path": "some-path",
- "path.basename": "some-path",
- "path[0]": "some-path",
- "path.basenameNormalized": "some-path",
- "path.filename": "values.yaml",
- "path.filenameNormalized": "values.yaml",
- },
- {
- "cluster.owner": "foo.bar@example.com",
- "cluster.name": "staging",
- "cluster.address": "https://kubernetes.default.svc",
- "path": "some-path/staging",
- "path.basename": "staging",
- "path[0]": "some-path",
- "path[1]": "staging",
- "path.basenameNormalized": "staging",
- "path.filename": "values.yaml",
- "path.filenameNormalized": "values.yaml",
- },
- },
- expectedError: nil,
- },
- {
- name: "test to verify the solution for Git File Generator Problem",
- files: []v1alpha1.GitFileGeneratorItem{{Path: "cluster-charts/*/*/values.yaml"}, {Path: "cluster-charts/*/values.yaml", Exclude: true}},
- includePattern: []string{"cluster-charts/*/*/values.yaml"},
- excludePattern: []string{"cluster-charts/*/values.yaml"},
- includeFiles: map[string][]byte{
- "cluster-charts/cluster1/mychart/values.yaml": []byte(`
-env: staging
-`),
- "cluster-charts/cluster1/myotherchart/values.yaml": []byte(`
-env: prod
-`),
- "cluster-charts/cluster1/mychart/charts/mysubchart/values.yaml": []byte(``),
- },
- excludeFiles: map[string][]byte{
- "cluster-charts/cluster2/values.yaml": []byte(`
-env: dev
-`),
- "cluster-charts/cluster1/mychart/values.yaml": []byte(`
-env: staging
-`),
- "cluster-charts/cluster1/myotherchart/values.yaml": []byte(`
-env: prod
-`),
- "cluster-charts/cluster1/mychart/charts/mysubchart/values.yaml": []byte(``),
- },
- noMatchFiles: map[string][]byte{
- "cluster-charts/cluster1/mychart/charts/mysubchart/values.yaml": []byte(`
-env: testing
-`),
- },
- repoPathsError: nil,
- expected: []map[string]any{},
- expectedError: nil,
- },
- }
- for _, testCase := range cases {
- testCaseCopy := testCase
-
- t.Run(testCaseCopy.name, func(t *testing.T) {
- t.Parallel()
-
- argoCDServiceMock := mocks.Repos{}
-
- // IMPORTANT: we try to get the files from the repo server that matches the patterns
- // If we find those files also satisfy the exclude pattern, we remove them from map
- // This is generally done by the g.repos.GetFiles() function.
- // With the below mock setup, we make sure that if the GetFiles() function gets called
- // for a include or exclude pattern, it should always return the includeFiles or excludeFiles.
- for _, pattern := range testCaseCopy.excludePattern {
- argoCDServiceMock.
- On("GetFiles", mock.Anything, mock.Anything, mock.Anything, mock.Anything, pattern, mock.Anything, mock.Anything).
- Return(testCaseCopy.excludeFiles, testCaseCopy.repoPathsError)
- }
-
- for _, pattern := range testCaseCopy.includePattern {
- argoCDServiceMock.
- On("GetFiles", mock.Anything, mock.Anything, mock.Anything, mock.Anything, pattern, mock.Anything, mock.Anything).
- Return(testCaseCopy.includeFiles, testCaseCopy.repoPathsError)
- }
-
- gitGenerator := NewGitGenerator(&argoCDServiceMock, "")
- applicationSetInfo := v1alpha1.ApplicationSet{
- ObjectMeta: metav1.ObjectMeta{
- Name: "set",
- },
- Spec: v1alpha1.ApplicationSetSpec{
- Generators: []v1alpha1.ApplicationSetGenerator{{
- Git: &v1alpha1.GitGenerator{
- RepoURL: "RepoURL",
- Revision: "Revision",
- Files: testCaseCopy.files,
- Values: testCaseCopy.values,
- },
- }},
- },
- }
-
- scheme := runtime.NewScheme()
- err := v1alpha1.AddToScheme(scheme)
- require.NoError(t, err)
- appProject := v1alpha1.AppProject{}
-
- client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(&appProject).Build()
-
- got, err := gitGenerator.GenerateParams(&applicationSetInfo.Spec.Generators[0], &applicationSetInfo, client)
-
- if testCaseCopy.expectedError != nil {
- require.EqualError(t, err, testCaseCopy.expectedError.Error())
- } else {
- require.NoError(t, err)
- assert.ElementsMatch(t, testCaseCopy.expected, got)
- }
-
- argoCDServiceMock.AssertExpectations(t)
- })
- }
-}
-
-// TestGitGeneratorParamsFromFilesWithExcludeOption tests the params values generated by git file generator
-// when exclude option is set to true. It gives the result files based on new globbing pattern - doublestar package
-func TestGitGeneratorParamsFromFilesWithExcludeOptionGoTemplate(t *testing.T) {
- cases := []struct {
- name string
- // files is the list of paths/globs to match
- files []v1alpha1.GitFileGeneratorItem
- // includePattern contains a list of file patterns that needs to be included
- includePattern []string
- // excludePattern contains a list of file patterns that needs to be excluded
- excludePattern []string
- // includeFiles is a map with key as absolute path to file and value as the content in bytes that satisfies the includePattern
- includeFiles map[string][]byte
- // excludeFiles is a map with key as absolute path to file and value as the content in bytes that satisfies the excludePattern
- // This means all the files should be excluded
- excludeFiles map[string][]byte
- // if repoPathsError is non-nil, the call to GetPaths(...) will return this error value
- repoPathsError error
- values map[string]string
- expected []map[string]any
- expectedError error
- }{
- {
- name: "filter files according to file-path with exclude",
- files: []v1alpha1.GitFileGeneratorItem{
- {
- Path: "**/config.json",
- },
- {
- Path: "p1/**/config.json",
- Exclude: true,
- },
- },
- includePattern: []string{"**/config.json"},
- excludePattern: []string{"p1/**/config.json"},
- includeFiles: map[string][]byte{
- "cluster-config/production/config.json": []byte(`{
- "cluster": {
- "owner": "john.doe@example.com",
- "name": "production",
- "address": "https://kubernetes.default.svc"
- },
- "key1": "val1",
- "key2": {
- "key2_1": "val2_1",
- "key2_2": {
- "key2_2_1": "val2_2_1"
- }
- },
- "key3": 123
-}
-`),
- },
- excludeFiles: map[string][]byte{
- "p1/p2/config.json": []byte(`{
- "service": {
- "maintainer": "dev.team@example.com",
- "serviceName": "auth-service",
- "endpoint": "http://auth.internal.svc",
- "config": {
- "retries": 5,
- "timeout": "30s"
- }
- }
- }
-`),
- },
- repoPathsError: nil,
- expected: []map[string]any{
- {
- "cluster": map[string]any{
- "owner": "john.doe@example.com",
- "name": "production",
- "address": "https://kubernetes.default.svc",
- },
- "key1": "val1",
- "key2": map[string]any{
- "key2_1": "val2_1",
- "key2_2": map[string]any{
- "key2_2_1": "val2_2_1",
- },
- },
- "key3": float64(123),
- "path": map[string]any{
- "path": "cluster-config/production",
- "basename": "production",
- "filename": "config.json",
- "basenameNormalized": "production",
- "filenameNormalized": "config.json",
- "segments": []string{
- "cluster-config",
- "production",
- },
- },
- },
- },
- expectedError: nil,
- },
- {
- name: "filter files according to multiple file-paths with exclude",
- files: []v1alpha1.GitFileGeneratorItem{
- {Path: "**/config.json"},
- {Path: "p1/app2/config.json", Exclude: true},
- {Path: "p1/app3/config.json", Exclude: true},
- },
- includePattern: []string{"**/config.json"},
- excludePattern: []string{"p1/app2/config.json", "p1/app3/config.json"},
- includeFiles: map[string][]byte{
- "p1/config.json": []byte(`{
- "cluster": {
- "owner": "john.doe@example.com",
- "name": "production",
- "address": "https://kubernetes.default.svc",
- "inner": {
- "one" : "two"
- }
- }
-}`),
- },
- excludeFiles: map[string][]byte{
- "p1/app2/config.json": []byte(`{
- "database": {
- "admin": "alice.smith@example.com",
- "env": "staging",
- "url": "postgres://db.internal.svc:5432",
- "settings": {
- "replicas": 3,
- "backup": "enabled"
- }
- }
- }
-`),
- "p1/app3/config.json": []byte(`{
- "storage": {
- "owner": "charlie.brown@example.com",
- "bucketName": "app-assets",
- "region": "us-west-2",
- "options": {
- "versioning": true,
- "encryption": "AES256"
- }
- }
- }
-`),
- },
- repoPathsError: nil,
- expected: []map[string]any{
- {
- "cluster": map[string]any{
- "owner": "john.doe@example.com",
- "name": "production",
- "address": "https://kubernetes.default.svc",
- "inner": map[string]any{
- "one": "two",
- },
- },
- "path": map[string]any{
- "path": "p1",
- "basename": "p1",
- "filename": "config.json",
- "basenameNormalized": "p1",
- "filenameNormalized": "config.json",
- "segments": []string{
- "p1",
- },
- },
- },
- },
- expectedError: nil,
- },
- }
- for _, testCase := range cases {
- testCaseCopy := testCase
-
- t.Run(testCaseCopy.name, func(t *testing.T) {
- t.Parallel()
-
- argoCDServiceMock := mocks.Repos{}
- // IMPORTANT: we try to get the files from the repo server that matches the patterns
- // If we find those files also satisfy the exclude pattern, we remove them from map
- // This is generally done by the g.repos.GetFiles() function.
- // With the below mock setup, we make sure that if the GetFiles() function gets called
- // for a include or exclude pattern, it should always return the includeFiles or excludeFiles.
- for _, pattern := range testCaseCopy.excludePattern {
- argoCDServiceMock.
- On("GetFiles", mock.Anything, mock.Anything, mock.Anything, mock.Anything, pattern, mock.Anything, mock.Anything).
- Return(testCaseCopy.excludeFiles, testCaseCopy.repoPathsError)
- }
-
- for _, pattern := range testCaseCopy.includePattern {
- argoCDServiceMock.
- On("GetFiles", mock.Anything, mock.Anything, mock.Anything, mock.Anything, pattern, mock.Anything, mock.Anything).
- Return(testCaseCopy.includeFiles, testCaseCopy.repoPathsError)
- }
-
- gitGenerator := NewGitGenerator(&argoCDServiceMock, "")
- applicationSetInfo := v1alpha1.ApplicationSet{
- ObjectMeta: metav1.ObjectMeta{
- Name: "set",
- },
- Spec: v1alpha1.ApplicationSetSpec{
- GoTemplate: true,
- Generators: []v1alpha1.ApplicationSetGenerator{{
- Git: &v1alpha1.GitGenerator{
- RepoURL: "RepoURL",
- Revision: "Revision",
- Files: testCaseCopy.files,
- },
- }},
- },
- }
-
- scheme := runtime.NewScheme()
- err := v1alpha1.AddToScheme(scheme)
- require.NoError(t, err)
- appProject := v1alpha1.AppProject{}
+ appProject := argoprojiov1alpha1.AppProject{}
client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(&appProject).Build()
got, err := gitGenerator.GenerateParams(&applicationSetInfo.Spec.Generators[0], &applicationSetInfo, client)
+ fmt.Println(got, err)
if testCaseCopy.expectedError != nil {
require.EqualError(t, err, testCaseCopy.expectedError.Error())
@@ -1946,17 +1032,17 @@ func TestGitGenerateParamsFromFilesGoTemplate(t *testing.T) {
cases := []struct {
name string
// files is the list of paths/globs to match
- files []v1alpha1.GitFileGeneratorItem
+ files []argoprojiov1alpha1.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
repoPathsError error
- expected []map[string]any
+ expected []map[string]interface{}
expectedError error
}{
{
name: "happy flow: create params from git files",
- files: []v1alpha1.GitFileGeneratorItem{{Path: "**/config.json"}},
+ files: []argoprojiov1alpha1.GitFileGeneratorItem{{Path: "**/config.json"}},
repoFileContents: map[string][]byte{
"cluster-config/production/config.json": []byte(`{
"cluster": {
@@ -1982,22 +1068,22 @@ func TestGitGenerateParamsFromFilesGoTemplate(t *testing.T) {
}`),
},
repoPathsError: nil,
- expected: []map[string]any{
+ expected: []map[string]interface{}{
{
- "cluster": map[string]any{
+ "cluster": map[string]interface{}{
"owner": "john.doe@example.com",
"name": "production",
"address": "https://kubernetes.default.svc",
},
"key1": "val1",
- "key2": map[string]any{
+ "key2": map[string]interface{}{
"key2_1": "val2_1",
- "key2_2": map[string]any{
+ "key2_2": map[string]interface{}{
"key2_2_1": "val2_2_1",
},
},
"key3": float64(123),
- "path": map[string]any{
+ "path": map[string]interface{}{
"path": "cluster-config/production",
"basename": "production",
"filename": "config.json",
@@ -2010,12 +1096,12 @@ func TestGitGenerateParamsFromFilesGoTemplate(t *testing.T) {
},
},
{
- "cluster": map[string]any{
+ "cluster": map[string]interface{}{
"owner": "foo.bar@example.com",
"name": "staging",
"address": "https://kubernetes.default.svc",
},
- "path": map[string]any{
+ "path": map[string]interface{}{
"path": "cluster-config/staging",
"basename": "staging",
"filename": "config.json",
@@ -2032,25 +1118,25 @@ func TestGitGenerateParamsFromFilesGoTemplate(t *testing.T) {
},
{
name: "handles error during getting repo paths",
- files: []v1alpha1.GitFileGeneratorItem{{Path: "**/config.json"}},
+ files: []argoprojiov1alpha1.GitFileGeneratorItem{{Path: "**/config.json"}},
repoFileContents: map[string][]byte{},
- repoPathsError: errors.New("paths error"),
- expected: []map[string]any{},
- expectedError: errors.New("error generating params from git: paths error"),
+ repoPathsError: fmt.Errorf("paths error"),
+ expected: []map[string]interface{}{},
+ expectedError: fmt.Errorf("error generating params from git: paths error"),
},
{
name: "test invalid JSON file returns error",
- files: []v1alpha1.GitFileGeneratorItem{{Path: "**/config.json"}},
+ files: []argoprojiov1alpha1.GitFileGeneratorItem{{Path: "**/config.json"}},
repoFileContents: map[string][]byte{
"cluster-config/production/config.json": []byte(`invalid json file`),
},
repoPathsError: nil,
- 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 {}"),
+ expected: []map[string]interface{}{},
+ expectedError: fmt.Errorf("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 {}"),
},
{
name: "test JSON array",
- files: []v1alpha1.GitFileGeneratorItem{{Path: "**/config.json"}},
+ files: []argoprojiov1alpha1.GitFileGeneratorItem{{Path: "**/config.json"}},
repoFileContents: map[string][]byte{
"cluster-config/production/config.json": []byte(`
[
@@ -2074,17 +1160,17 @@ func TestGitGenerateParamsFromFilesGoTemplate(t *testing.T) {
]`),
},
repoPathsError: nil,
- expected: []map[string]any{
+ expected: []map[string]interface{}{
{
- "cluster": map[string]any{
+ "cluster": map[string]interface{}{
"owner": "john.doe@example.com",
"name": "production",
"address": "https://kubernetes.default.svc",
- "inner": map[string]any{
+ "inner": map[string]interface{}{
"one": "two",
},
},
- "path": map[string]any{
+ "path": map[string]interface{}{
"path": "cluster-config/production",
"basename": "production",
"filename": "config.json",
@@ -2097,12 +1183,12 @@ func TestGitGenerateParamsFromFilesGoTemplate(t *testing.T) {
},
},
{
- "cluster": map[string]any{
+ "cluster": map[string]interface{}{
"owner": "john.doe@example.com",
"name": "staging",
"address": "https://kubernetes.default.svc",
},
- "path": map[string]any{
+ "path": map[string]interface{}{
"path": "cluster-config/production",
"basename": "production",
"filename": "config.json",
@@ -2119,7 +1205,7 @@ func TestGitGenerateParamsFromFilesGoTemplate(t *testing.T) {
},
{
name: "Test YAML flow",
- files: []v1alpha1.GitFileGeneratorItem{{Path: "**/config.yaml"}},
+ files: []argoprojiov1alpha1.GitFileGeneratorItem{{Path: "**/config.yaml"}},
repoFileContents: map[string][]byte{
"cluster-config/production/config.yaml": []byte(`
cluster:
@@ -2140,21 +1226,21 @@ cluster:
`),
},
repoPathsError: nil,
- expected: []map[string]any{
+ expected: []map[string]interface{}{
{
- "cluster": map[string]any{
+ "cluster": map[string]interface{}{
"owner": "john.doe@example.com",
"name": "production",
"address": "https://kubernetes.default.svc",
},
"key1": "val1",
- "key2": map[string]any{
+ "key2": map[string]interface{}{
"key2_1": "val2_1",
- "key2_2": map[string]any{
+ "key2_2": map[string]interface{}{
"key2_2_1": "val2_2_1",
},
},
- "path": map[string]any{
+ "path": map[string]interface{}{
"path": "cluster-config/production",
"basename": "production",
"filename": "config.yaml",
@@ -2167,12 +1253,12 @@ cluster:
},
},
{
- "cluster": map[string]any{
+ "cluster": map[string]interface{}{
"owner": "foo.bar@example.com",
"name": "staging",
"address": "https://kubernetes.default.svc",
},
- "path": map[string]any{
+ "path": map[string]interface{}{
"path": "cluster-config/staging",
"basename": "staging",
"filename": "config.yaml",
@@ -2189,7 +1275,7 @@ cluster:
},
{
name: "test YAML array",
- files: []v1alpha1.GitFileGeneratorItem{{Path: "**/config.yaml"}},
+ files: []argoprojiov1alpha1.GitFileGeneratorItem{{Path: "**/config.yaml"}},
repoFileContents: map[string][]byte{
"cluster-config/production/config.yaml": []byte(`
- cluster:
@@ -2204,17 +1290,17 @@ cluster:
address: https://kubernetes.default.svc`),
},
repoPathsError: nil,
- expected: []map[string]any{
+ expected: []map[string]interface{}{
{
- "cluster": map[string]any{
+ "cluster": map[string]interface{}{
"owner": "john.doe@example.com",
"name": "production",
"address": "https://kubernetes.default.svc",
- "inner": map[string]any{
+ "inner": map[string]interface{}{
"one": "two",
},
},
- "path": map[string]any{
+ "path": map[string]interface{}{
"path": "cluster-config/production",
"basename": "production",
"filename": "config.yaml",
@@ -2227,12 +1313,12 @@ cluster:
},
},
{
- "cluster": map[string]any{
+ "cluster": map[string]interface{}{
"owner": "john.doe@example.com",
"name": "staging",
"address": "https://kubernetes.default.svc",
},
- "path": map[string]any{
+ "path": map[string]interface{}{
"path": "cluster-config/production",
"basename": "production",
"filename": "config.yaml",
@@ -2256,18 +1342,18 @@ cluster:
t.Parallel()
argoCDServiceMock := mocks.Repos{}
- argoCDServiceMock.On("GetFiles", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).
+ argoCDServiceMock.On("GetFiles", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).
Return(testCaseCopy.repoFileContents, testCaseCopy.repoPathsError)
gitGenerator := NewGitGenerator(&argoCDServiceMock, "")
- applicationSetInfo := v1alpha1.ApplicationSet{
+ applicationSetInfo := argoprojiov1alpha1.ApplicationSet{
ObjectMeta: metav1.ObjectMeta{
Name: "set",
},
- Spec: v1alpha1.ApplicationSetSpec{
+ Spec: argoprojiov1alpha1.ApplicationSetSpec{
GoTemplate: true,
- Generators: []v1alpha1.ApplicationSetGenerator{{
- Git: &v1alpha1.GitGenerator{
+ Generators: []argoprojiov1alpha1.ApplicationSetGenerator{{
+ Git: &argoprojiov1alpha1.GitGenerator{
RepoURL: "RepoURL",
Revision: "Revision",
Files: testCaseCopy.files,
@@ -2279,11 +1365,12 @@ cluster:
scheme := runtime.NewScheme()
err := v1alpha1.AddToScheme(scheme)
require.NoError(t, err)
- appProject := v1alpha1.AppProject{}
+ appProject := argoprojiov1alpha1.AppProject{}
client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(&appProject).Build()
got, err := gitGenerator.GenerateParams(&applicationSetInfo.Spec.Generators[0], &applicationSetInfo, client)
+ fmt.Println(got, err)
if testCaseCopy.expectedError != nil {
require.EqualError(t, err, testCaseCopy.expectedError.Error())
@@ -2300,17 +1387,15 @@ cluster:
func TestGitGenerator_GenerateParams(t *testing.T) {
cases := []struct {
name string
- appProject v1alpha1.AppProject
- directories []v1alpha1.GitDirectoryGeneratorItem
+ directories []argoprojiov1alpha1.GitDirectoryGeneratorItem
pathParamPrefix string
repoApps []string
repoPathsError error
repoFileContents map[string][]byte
values map[string]string
- expected []map[string]any
+ expected []map[string]interface{}
expectedError error
- expectedProject *string
- appset v1alpha1.ApplicationSet
+ appset argoprojiov1alpha1.ApplicationSet
callGetDirectories bool
}{
{
@@ -2319,32 +1404,32 @@ func TestGitGenerator_GenerateParams(t *testing.T) {
"app1",
},
repoPathsError: nil,
- appset: v1alpha1.ApplicationSet{
+ appset: argoprojiov1alpha1.ApplicationSet{
ObjectMeta: metav1.ObjectMeta{
Name: "set",
Namespace: "namespace",
},
- Spec: v1alpha1.ApplicationSetSpec{
- Generators: []v1alpha1.ApplicationSetGenerator{{
- Git: &v1alpha1.GitGenerator{
+ Spec: argoprojiov1alpha1.ApplicationSetSpec{
+ Generators: []argoprojiov1alpha1.ApplicationSetGenerator{{
+ Git: &argoprojiov1alpha1.GitGenerator{
RepoURL: "RepoURL",
Revision: "Revision",
- Directories: []v1alpha1.GitDirectoryGeneratorItem{{Path: "*"}},
+ Directories: []argoprojiov1alpha1.GitDirectoryGeneratorItem{{Path: "*"}},
PathParamPrefix: "",
Values: map[string]string{
"foo": "bar",
},
},
}},
- Template: v1alpha1.ApplicationSetTemplate{
- Spec: v1alpha1.ApplicationSpec{
+ Template: argoprojiov1alpha1.ApplicationSetTemplate{
+ Spec: argoprojiov1alpha1.ApplicationSpec{
Project: "{{.project}}",
},
},
},
},
callGetDirectories: true,
- expected: []map[string]any{{"path": "app1", "path.basename": "app1", "path.basenameNormalized": "app1", "path[0]": "app1", "values.foo": "bar"}},
+ expected: []map[string]interface{}{{"path": "app1", "path.basename": "app1", "path.basenameNormalized": "app1", "path[0]": "app1", "values.foo": "bar"}},
expectedError: nil,
},
{
@@ -2353,130 +1438,49 @@ func TestGitGenerator_GenerateParams(t *testing.T) {
"app1",
},
repoPathsError: nil,
- appset: v1alpha1.ApplicationSet{
+ appset: argoprojiov1alpha1.ApplicationSet{
ObjectMeta: metav1.ObjectMeta{
Name: "set",
Namespace: "namespace",
},
- Spec: v1alpha1.ApplicationSetSpec{
- Generators: []v1alpha1.ApplicationSetGenerator{{
- Git: &v1alpha1.GitGenerator{
+ Spec: argoprojiov1alpha1.ApplicationSetSpec{
+ Generators: []argoprojiov1alpha1.ApplicationSetGenerator{{
+ Git: &argoprojiov1alpha1.GitGenerator{
RepoURL: "RepoURL",
Revision: "Revision",
- Directories: []v1alpha1.GitDirectoryGeneratorItem{{Path: "*"}},
+ Directories: []argoprojiov1alpha1.GitDirectoryGeneratorItem{{Path: "*"}},
PathParamPrefix: "",
Values: map[string]string{
"foo": "bar",
},
},
}},
- Template: v1alpha1.ApplicationSetTemplate{
- Spec: v1alpha1.ApplicationSpec{
+ Template: argoprojiov1alpha1.ApplicationSetTemplate{
+ Spec: argoprojiov1alpha1.ApplicationSpec{
Project: "project",
},
},
},
},
callGetDirectories: false,
- 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"),
- },
- {
- name: "Project field is not templated - verify that project is passed through to repo-server as-is",
- repoApps: []string{
- "app1",
- },
- callGetDirectories: true,
- appProject: v1alpha1.AppProject{
- TypeMeta: metav1.TypeMeta{},
- ObjectMeta: metav1.ObjectMeta{
- Name: "project",
- Namespace: "argocd",
- },
- },
- appset: v1alpha1.ApplicationSet{
- ObjectMeta: metav1.ObjectMeta{
- Name: "set",
- Namespace: "namespace",
- },
- Spec: v1alpha1.ApplicationSetSpec{
- Generators: []v1alpha1.ApplicationSetGenerator{{
- Git: &v1alpha1.GitGenerator{
- RepoURL: "RepoURL",
- Revision: "Revision",
- Directories: []v1alpha1.GitDirectoryGeneratorItem{{Path: "*"}},
- PathParamPrefix: "",
- Values: map[string]string{
- "foo": "bar",
- },
- },
- }},
- Template: v1alpha1.ApplicationSetTemplate{
- Spec: v1alpha1.ApplicationSpec{
- Project: "project",
- },
- },
- },
- },
- expected: []map[string]any{{"path": "app1", "path.basename": "app1", "path.basenameNormalized": "app1", "path[0]": "app1", "values.foo": "bar"}},
- expectedProject: ptr.To("project"),
- expectedError: nil,
- },
- {
- name: "Project field is templated - verify that project is passed through to repo-server as empty string",
- repoApps: []string{
- "app1",
- },
- callGetDirectories: true,
- appset: v1alpha1.ApplicationSet{
- ObjectMeta: metav1.ObjectMeta{
- Name: "set",
- Namespace: "namespace",
- },
- Spec: v1alpha1.ApplicationSetSpec{
- Generators: []v1alpha1.ApplicationSetGenerator{{
- Git: &v1alpha1.GitGenerator{
- RepoURL: "RepoURL",
- Revision: "Revision",
- Directories: []v1alpha1.GitDirectoryGeneratorItem{{Path: "*"}},
- PathParamPrefix: "",
- Values: map[string]string{
- "foo": "bar",
- },
- },
- }},
- Template: v1alpha1.ApplicationSetTemplate{
- Spec: v1alpha1.ApplicationSpec{
- Project: "{{.project}}",
- },
- },
- },
- },
- expected: []map[string]any{{"path": "app1", "path.basename": "app1", "path.basenameNormalized": "app1", "path[0]": "app1", "values.foo": "bar"}},
- expectedProject: ptr.To(""),
- expectedError: nil,
+ expected: []map[string]interface{}{{"path": "app1", "path.basename": "app1", "path.basenameNormalized": "app1", "path[0]": "app1", "values.foo": "bar"}},
+ expectedError: fmt.Errorf("error getting project project: appprojects.argoproj.io \"project\" not found"),
},
}
for _, testCase := range cases {
argoCDServiceMock := mocks.Repos{}
if testCase.callGetDirectories {
- var project any
- if testCase.expectedProject != nil {
- project = *testCase.expectedProject
- } else {
- project = mock.Anything
- }
-
- argoCDServiceMock.On("GetDirectories", mock.Anything, mock.Anything, mock.Anything, project, mock.Anything, mock.Anything).Return(testCase.repoApps, testCase.repoPathsError)
+ argoCDServiceMock.On("GetDirectories", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(testCase.repoApps, testCase.repoPathsError)
}
- gitGenerator := NewGitGenerator(&argoCDServiceMock, "argocd")
+ gitGenerator := NewGitGenerator(&argoCDServiceMock, "namespace")
scheme := runtime.NewScheme()
err := v1alpha1.AddToScheme(scheme)
require.NoError(t, err)
+ appProject := argoprojiov1alpha1.AppProject{}
- client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(&testCase.appProject).Build()
+ client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(&appProject).Build()
got, err := gitGenerator.GenerateParams(&testCase.appset.Spec.Generators[0], &testCase.appset, client)
diff --git a/applicationset/generators/interface.go b/applicationset/generators/interface.go
index 1928920023..88853c73b2 100644
--- a/applicationset/generators/interface.go
+++ b/applicationset/generators/interface.go
@@ -1,13 +1,13 @@
package generators
import (
- "errors"
+ "fmt"
"time"
"sigs.k8s.io/controller-runtime/pkg/client"
- argoprojiov1alpha1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- "github.com/argoproj/argo-cd/v3/util/env"
+ argoprojiov1alpha1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/util/env"
)
// Generator defines the interface implemented by all ApplicationSet generators.
@@ -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]any, error)
+ GenerateParams(appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator, applicationSetInfo *argoprojiov1alpha1.ApplicationSet, client client.Client) ([]map[string]interface{}, 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.
@@ -27,15 +27,15 @@ type Generator interface {
}
var (
- ErrEmptyAppSetGenerator = errors.New("ApplicationSet is empty")
- NoRequeueAfter time.Duration
+ EmptyAppSetGeneratorError = fmt.Errorf("ApplicationSet is empty")
+ NoRequeueAfter time.Duration
)
const (
- DefaultRequeueAfter = 3 * time.Minute
+ DefaultRequeueAfterSeconds = 3 * time.Minute
)
func getDefaultRequeueAfter() time.Duration {
// Default is 3 minutes, min is 1 second, max is 1 year
- return env.ParseDurationFromEnv("ARGOCD_APPLICATIONSET_CONTROLLER_REQUEUE_AFTER", DefaultRequeueAfter, 1*time.Second, 8760*time.Hour)
+ return env.ParseDurationFromEnv("ARGOCD_APPLICATIONSET_CONTROLLER_REQUEUE_AFTER", DefaultRequeueAfterSeconds, 1*time.Second, 8760*time.Hour)
}
diff --git a/applicationset/generators/interface_test.go b/applicationset/generators/interface_test.go
index f85c7bf004..d27111bc14 100644
--- a/applicationset/generators/interface_test.go
+++ b/applicationset/generators/interface_test.go
@@ -13,12 +13,12 @@ func Test_getDefaultRequeueAfter(t *testing.T) {
requeueAfterEnv string
want time.Duration
}{
- {name: "Default", requeueAfterEnv: "", want: DefaultRequeueAfter},
+ {name: "Default", requeueAfterEnv: "", want: DefaultRequeueAfterSeconds},
{name: "Min", requeueAfterEnv: "1s", want: 1 * time.Second},
{name: "Max", requeueAfterEnv: "8760h", want: 8760 * time.Hour},
{name: "Override", requeueAfterEnv: "10m", want: 10 * time.Minute},
- {name: "LessThanMin", requeueAfterEnv: "1ms", want: DefaultRequeueAfter},
- {name: "MoreThanMax", requeueAfterEnv: "8761h", want: DefaultRequeueAfter},
+ {name: "LessThanMin", requeueAfterEnv: "1ms", want: DefaultRequeueAfterSeconds},
+ {name: "MoreThanMax", requeueAfterEnv: "8761h", want: DefaultRequeueAfterSeconds},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
diff --git a/applicationset/generators/list.go b/applicationset/generators/list.go
index 36b67a7bfa..fad6a6af5c 100644
--- a/applicationset/generators/list.go
+++ b/applicationset/generators/list.go
@@ -2,14 +2,13 @@ package generators
import (
"encoding/json"
- "errors"
"fmt"
"time"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/yaml"
- argoprojiov1alpha1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ argoprojiov1alpha1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
)
var _ Generator = (*ListGenerator)(nil)
@@ -21,7 +20,7 @@ func NewListGenerator() Generator {
return g
}
-func (g *ListGenerator) GetRequeueAfter(_ *argoprojiov1alpha1.ApplicationSetGenerator) time.Duration {
+func (g *ListGenerator) GetRequeueAfter(appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator) time.Duration {
return NoRequeueAfter
}
@@ -29,20 +28,20 @@ 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]any, error) {
+func (g *ListGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator, appSet *argoprojiov1alpha1.ApplicationSet, _ client.Client) ([]map[string]interface{}, error) {
if appSetGenerator == nil {
- return nil, ErrEmptyAppSetGenerator
+ return nil, EmptyAppSetGeneratorError
}
if appSetGenerator.List == nil {
- return nil, ErrEmptyAppSetGenerator
+ return nil, EmptyAppSetGeneratorError
}
- res := make([]map[string]any, len(appSetGenerator.List.Elements))
+ res := make([]map[string]interface{}, len(appSetGenerator.List.Elements))
for i, tmpItem := range appSetGenerator.List.Elements {
- params := map[string]any{}
- var element map[string]any
+ params := map[string]interface{}{}
+ var element map[string]interface{}
err := json.Unmarshal(tmpItem.Raw, &element)
if err != nil {
return nil, fmt.Errorf("error unmarshling list element %w", err)
@@ -53,16 +52,16 @@ func (g *ListGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha1.Appli
} else {
for key, value := range element {
if key == "values" {
- values, ok := (value).(map[string]any)
+ values, ok := (value).(map[string]interface{})
if !ok {
- return nil, errors.New("error parsing values map")
+ return nil, fmt.Errorf("error parsing values map")
}
for k, v := range values {
value, ok := v.(string)
if !ok {
return nil, fmt.Errorf("error parsing value as string %w", err)
}
- params["values."+k] = value
+ params[fmt.Sprintf("values.%s", k)] = value
}
} else {
v, ok := value.(string)
@@ -78,7 +77,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]any
+ var yamlElements []map[string]interface{}
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 2952878baf..5a3b1d88dd 100644
--- a/applicationset/generators/list_test.go
+++ b/applicationset/generators/list_test.go
@@ -8,20 +8,20 @@ import (
apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
- argoprojiov1alpha1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ argoprojiov1alpha1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
)
func TestGenerateListParams(t *testing.T) {
testCases := []struct {
elements []apiextensionsv1.JSON
- expected []map[string]any
+ expected []map[string]interface{}
}{
{
elements: []apiextensionsv1.JSON{{Raw: []byte(`{"cluster": "cluster","url": "url"}`)}},
- expected: []map[string]any{{"cluster": "cluster", "url": "url"}},
+ expected: []map[string]interface{}{{"cluster": "cluster", "url": "url"}},
}, {
elements: []apiextensionsv1.JSON{{Raw: []byte(`{"cluster": "cluster","url": "url","values":{"foo":"bar"}}`)}},
- expected: []map[string]any{{"cluster": "cluster", "url": "url", "values.foo": "bar"}},
+ expected: []map[string]interface{}{{"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]any
+ expected []map[string]interface{}
}{
{
elements: []apiextensionsv1.JSON{{Raw: []byte(`{"cluster": "cluster","url": "url"}`)}},
- expected: []map[string]any{{"cluster": "cluster", "url": "url"}},
+ expected: []map[string]interface{}{{"cluster": "cluster", "url": "url"}},
}, {
elements: []apiextensionsv1.JSON{{Raw: []byte(`{"cluster": "cluster","url": "url","values":{"foo":"bar"}}`)}},
- expected: []map[string]any{{"cluster": "cluster", "url": "url", "values": map[string]any{"foo": "bar"}}},
+ expected: []map[string]interface{}{{"cluster": "cluster", "url": "url", "values": map[string]interface{}{"foo": "bar"}}},
},
}
diff --git a/applicationset/generators/matrix.go b/applicationset/generators/matrix.go
index 64d23b8760..2a44d97b71 100644
--- a/applicationset/generators/matrix.go
+++ b/applicationset/generators/matrix.go
@@ -1,23 +1,24 @@
package generators
import (
- "errors"
"fmt"
"time"
- "dario.cat/mergo"
+ "github.com/imdario/mergo"
"sigs.k8s.io/controller-runtime/pkg/client"
- "github.com/argoproj/argo-cd/v3/applicationset/utils"
- argoprojiov1alpha1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/applicationset/utils"
+ argoprojiov1alpha1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+
+ log "github.com/sirupsen/logrus"
)
var _ Generator = (*MatrixGenerator)(nil)
var (
- ErrMoreThanTwoGenerators = errors.New("found more than two generators, Matrix support only two")
- ErrLessThanTwoGenerators = errors.New("found less than two generators, Matrix support only two")
- ErrMoreThenOneInnerGenerators = errors.New("found more than one generator in matrix.Generators")
+ ErrMoreThanTwoGenerators = fmt.Errorf("found more than two generators, Matrix support only two")
+ ErrLessThanTwoGenerators = fmt.Errorf("found less than two generators, Matrix support only two")
+ ErrMoreThenOneInnerGenerators = fmt.Errorf("found more than one generator in matrix.Generators")
)
type MatrixGenerator struct {
@@ -32,9 +33,9 @@ func NewMatrixGenerator(supportedGenerators map[string]Generator) Generator {
return m
}
-func (m *MatrixGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator, appSet *argoprojiov1alpha1.ApplicationSet, client client.Client) ([]map[string]any, error) {
+func (m *MatrixGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator, appSet *argoprojiov1alpha1.ApplicationSet, client client.Client) ([]map[string]interface{}, error) {
if appSetGenerator.Matrix == nil {
- return nil, ErrEmptyAppSetGenerator
+ return nil, EmptyAppSetGeneratorError
}
if len(appSetGenerator.Matrix.Generators) < 2 {
@@ -45,7 +46,7 @@ func (m *MatrixGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha1.App
return nil, ErrMoreThanTwoGenerators
}
- res := []map[string]any{}
+ res := []map[string]interface{}{}
g0, err := m.getParams(appSetGenerator.Matrix.Generators[0], appSet, nil, client)
if err != nil {
@@ -58,7 +59,7 @@ func (m *MatrixGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha1.App
}
for _, b := range g1 {
if appSet.Spec.GoTemplate {
- tmp := map[string]any{}
+ tmp := map[string]interface{}{}
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)
}
@@ -79,15 +80,27 @@ func (m *MatrixGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha1.App
return res, nil
}
-func (m *MatrixGenerator) getParams(appSetBaseGenerator argoprojiov1alpha1.ApplicationSetNestedGenerator, appSet *argoprojiov1alpha1.ApplicationSet, params map[string]any, client client.Client) ([]map[string]any, error) {
+func (m *MatrixGenerator) getParams(appSetBaseGenerator argoprojiov1alpha1.ApplicationSetNestedGenerator, appSet *argoprojiov1alpha1.ApplicationSet, params map[string]interface{}, client client.Client) ([]map[string]interface{}, error) {
matrixGen, err := getMatrixGenerator(appSetBaseGenerator)
if err != nil {
return nil, err
}
+ if matrixGen != nil && !appSet.Spec.ApplyNestedSelectors {
+ foundSelector := dropDisabledNestedSelectors(matrixGen.Generators)
+ if foundSelector {
+ log.Warnf("AppSet '%v' defines selector on nested matrix generator's generator without enabling them via 'spec.applyNestedSelectors', ignoring nested selectors", appSet.Name)
+ }
+ }
mergeGen, err := getMergeGenerator(appSetBaseGenerator)
if err != nil {
return nil, fmt.Errorf("error retrieving merge generator: %w", err)
}
+ if mergeGen != nil && !appSet.Spec.ApplyNestedSelectors {
+ foundSelector := dropDisabledNestedSelectors(mergeGen.Generators)
+ if foundSelector {
+ log.Warnf("AppSet '%v' defines selector on nested merge generator's generator without enabling them via 'spec.applyNestedSelectors', ignoring nested selectors", appSet.Name)
+ }
+ }
t, err := Transform(
argoprojiov1alpha1.ApplicationSetGenerator{
@@ -112,7 +125,7 @@ func (m *MatrixGenerator) getParams(appSetBaseGenerator argoprojiov1alpha1.Appli
}
if len(t) == 0 {
- return nil, errors.New("child generator generated no parameters")
+ return nil, fmt.Errorf("child generator generated no parameters")
}
if len(t) > 1 {
@@ -155,8 +168,9 @@ 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/matrix_test.go b/applicationset/generators/matrix_test.go
index 00b6353a50..dec0ab96b4 100644
--- a/applicationset/generators/matrix_test.go
+++ b/applicationset/generators/matrix_test.go
@@ -1,6 +1,7 @@
package generators
import (
+ "context"
"testing"
"time"
@@ -12,35 +13,36 @@ import (
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/fake"
- "github.com/argoproj/argo-cd/v3/applicationset/services/mocks"
+ "github.com/argoproj/argo-cd/v2/applicationset/services/mocks"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ "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 := &v1alpha1.GitGenerator{
+ gitGenerator := &argoprojiov1alpha1.GitGenerator{
RepoURL: "RepoURL",
Revision: "Revision",
- Directories: []v1alpha1.GitDirectoryGeneratorItem{{Path: "*"}},
+ Directories: []argoprojiov1alpha1.GitDirectoryGeneratorItem{{Path: "*"}},
}
- listGenerator := &v1alpha1.ListGenerator{
+ listGenerator := &argoprojiov1alpha1.ListGenerator{
Elements: []apiextensionsv1.JSON{{Raw: []byte(`{"cluster": "Cluster","url": "Url", "templated": "test-{{path.basenameNormalized}}"}`)}},
}
testCases := []struct {
name string
- baseGenerators []v1alpha1.ApplicationSetNestedGenerator
+ baseGenerators []argoprojiov1alpha1.ApplicationSetNestedGenerator
expectedErr error
- expected []map[string]any
+ expected []map[string]interface{}
}{
{
name: "happy flow - generate params",
- baseGenerators: []v1alpha1.ApplicationSetNestedGenerator{
+ baseGenerators: []argoprojiov1alpha1.ApplicationSetNestedGenerator{
{
Git: gitGenerator,
},
@@ -48,16 +50,16 @@ func TestMatrixGenerate(t *testing.T) {
List: listGenerator,
},
},
- expected: []map[string]any{
+ expected: []map[string]interface{}{
{"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"},
},
},
{
name: "happy flow - generate params from two lists",
- baseGenerators: []v1alpha1.ApplicationSetNestedGenerator{
+ baseGenerators: []argoprojiov1alpha1.ApplicationSetNestedGenerator{
{
- List: &v1alpha1.ListGenerator{
+ List: &argoprojiov1alpha1.ListGenerator{
Elements: []apiextensionsv1.JSON{
{Raw: []byte(`{"a": "1"}`)},
{Raw: []byte(`{"a": "2"}`)},
@@ -65,7 +67,7 @@ func TestMatrixGenerate(t *testing.T) {
},
},
{
- List: &v1alpha1.ListGenerator{
+ List: &argoprojiov1alpha1.ListGenerator{
Elements: []apiextensionsv1.JSON{
{Raw: []byte(`{"b": "1"}`)},
{Raw: []byte(`{"b": "2"}`)},
@@ -73,7 +75,7 @@ func TestMatrixGenerate(t *testing.T) {
},
},
},
- expected: []map[string]any{
+ expected: []map[string]interface{}{
{"a": "1", "b": "1"},
{"a": "1", "b": "2"},
{"a": "2", "b": "1"},
@@ -82,7 +84,7 @@ func TestMatrixGenerate(t *testing.T) {
},
{
name: "returns error if there is less than two base generators",
- baseGenerators: []v1alpha1.ApplicationSetNestedGenerator{
+ baseGenerators: []argoprojiov1alpha1.ApplicationSetNestedGenerator{
{
Git: gitGenerator,
},
@@ -91,7 +93,7 @@ func TestMatrixGenerate(t *testing.T) {
},
{
name: "returns error if there is more than two base generators",
- baseGenerators: []v1alpha1.ApplicationSetNestedGenerator{
+ baseGenerators: []argoprojiov1alpha1.ApplicationSetNestedGenerator{
{
List: listGenerator,
},
@@ -106,7 +108,7 @@ func TestMatrixGenerate(t *testing.T) {
},
{
name: "returns error if there is more than one inner generator in the first base generator",
- baseGenerators: []v1alpha1.ApplicationSetNestedGenerator{
+ baseGenerators: []argoprojiov1alpha1.ApplicationSetNestedGenerator{
{
Git: gitGenerator,
List: listGenerator,
@@ -119,7 +121,7 @@ func TestMatrixGenerate(t *testing.T) {
},
{
name: "returns error if there is more than one inner generator in the second base generator",
- baseGenerators: []v1alpha1.ApplicationSetNestedGenerator{
+ baseGenerators: []argoprojiov1alpha1.ApplicationSetNestedGenerator{
{
List: listGenerator,
},
@@ -137,19 +139,19 @@ func TestMatrixGenerate(t *testing.T) {
t.Run(testCaseCopy.name, func(t *testing.T) {
genMock := &generatorMock{}
- appSet := &v1alpha1.ApplicationSet{
+ appSet := &argoprojiov1alpha1.ApplicationSet{
ObjectMeta: metav1.ObjectMeta{
Name: "set",
},
- Spec: v1alpha1.ApplicationSetSpec{},
+ Spec: argoprojiov1alpha1.ApplicationSetSpec{},
}
for _, g := range testCaseCopy.baseGenerators {
- gitGeneratorSpec := v1alpha1.ApplicationSetGenerator{
+ gitGeneratorSpec := argoprojiov1alpha1.ApplicationSetGenerator{
Git: g.Git,
List: g.List,
}
- genMock.On("GenerateParams", mock.AnythingOfType("*v1alpha1.ApplicationSetGenerator"), appSet, mock.Anything).Return([]map[string]any{
+ genMock.On("GenerateParams", mock.AnythingOfType("*v1alpha1.ApplicationSetGenerator"), appSet, mock.Anything).Return([]map[string]interface{}{
{
"path": "app1",
"path.basename": "app1",
@@ -163,7 +165,7 @@ func TestMatrixGenerate(t *testing.T) {
}, nil)
genMock.On("GetTemplate", &gitGeneratorSpec).
- Return(&v1alpha1.ApplicationSetTemplate{})
+ Return(&argoprojiov1alpha1.ApplicationSetTemplate{})
}
matrixGenerator := NewMatrixGenerator(
@@ -173,10 +175,10 @@ func TestMatrixGenerate(t *testing.T) {
},
)
- got, err := matrixGenerator.GenerateParams(&v1alpha1.ApplicationSetGenerator{
- Matrix: &v1alpha1.MatrixGenerator{
+ got, err := matrixGenerator.GenerateParams(&argoprojiov1alpha1.ApplicationSetGenerator{
+ Matrix: &argoprojiov1alpha1.MatrixGenerator{
Generators: testCaseCopy.baseGenerators,
- Template: v1alpha1.ApplicationSetTemplate{},
+ Template: argoprojiov1alpha1.ApplicationSetTemplate{},
},
}, appSet, nil)
@@ -191,25 +193,25 @@ func TestMatrixGenerate(t *testing.T) {
}
func TestMatrixGenerateGoTemplate(t *testing.T) {
- gitGenerator := &v1alpha1.GitGenerator{
+ gitGenerator := &argoprojiov1alpha1.GitGenerator{
RepoURL: "RepoURL",
Revision: "Revision",
- Directories: []v1alpha1.GitDirectoryGeneratorItem{{Path: "*"}},
+ Directories: []argoprojiov1alpha1.GitDirectoryGeneratorItem{{Path: "*"}},
}
- listGenerator := &v1alpha1.ListGenerator{
+ listGenerator := &argoprojiov1alpha1.ListGenerator{
Elements: []apiextensionsv1.JSON{{Raw: []byte(`{"cluster": "Cluster","url": "Url"}`)}},
}
testCases := []struct {
name string
- baseGenerators []v1alpha1.ApplicationSetNestedGenerator
+ baseGenerators []argoprojiov1alpha1.ApplicationSetNestedGenerator
expectedErr error
- expected []map[string]any
+ expected []map[string]interface{}
}{
{
name: "happy flow - generate params",
- baseGenerators: []v1alpha1.ApplicationSetNestedGenerator{
+ baseGenerators: []argoprojiov1alpha1.ApplicationSetNestedGenerator{
{
Git: gitGenerator,
},
@@ -217,7 +219,7 @@ func TestMatrixGenerateGoTemplate(t *testing.T) {
List: listGenerator,
},
},
- expected: []map[string]any{
+ expected: []map[string]interface{}{
{
"path": map[string]string{
"path": "app1",
@@ -240,9 +242,9 @@ func TestMatrixGenerateGoTemplate(t *testing.T) {
},
{
name: "happy flow - generate params from two lists",
- baseGenerators: []v1alpha1.ApplicationSetNestedGenerator{
+ baseGenerators: []argoprojiov1alpha1.ApplicationSetNestedGenerator{
{
- List: &v1alpha1.ListGenerator{
+ List: &argoprojiov1alpha1.ListGenerator{
Elements: []apiextensionsv1.JSON{
{Raw: []byte(`{"a": "1"}`)},
{Raw: []byte(`{"a": "2"}`)},
@@ -250,7 +252,7 @@ func TestMatrixGenerateGoTemplate(t *testing.T) {
},
},
{
- List: &v1alpha1.ListGenerator{
+ List: &argoprojiov1alpha1.ListGenerator{
Elements: []apiextensionsv1.JSON{
{Raw: []byte(`{"b": "1"}`)},
{Raw: []byte(`{"b": "2"}`)},
@@ -258,7 +260,7 @@ func TestMatrixGenerateGoTemplate(t *testing.T) {
},
},
},
- expected: []map[string]any{
+ expected: []map[string]interface{}{
{"a": "1", "b": "1"},
{"a": "1", "b": "2"},
{"a": "2", "b": "1"},
@@ -267,29 +269,29 @@ func TestMatrixGenerateGoTemplate(t *testing.T) {
},
{
name: "parameter override: first list elements take precedence",
- baseGenerators: []v1alpha1.ApplicationSetNestedGenerator{
+ baseGenerators: []argoprojiov1alpha1.ApplicationSetNestedGenerator{
{
- List: &v1alpha1.ListGenerator{
+ List: &argoprojiov1alpha1.ListGenerator{
Elements: []apiextensionsv1.JSON{
{Raw: []byte(`{"booleanFalse": false, "booleanTrue": true, "stringFalse": "false", "stringTrue": "true"}`)},
},
},
},
{
- List: &v1alpha1.ListGenerator{
+ List: &argoprojiov1alpha1.ListGenerator{
Elements: []apiextensionsv1.JSON{
{Raw: []byte(`{"booleanFalse": true, "booleanTrue": false, "stringFalse": "true", "stringTrue": "false"}`)},
},
},
},
},
- expected: []map[string]any{
+ expected: []map[string]interface{}{
{"booleanFalse": false, "booleanTrue": true, "stringFalse": "false", "stringTrue": "true"},
},
},
{
name: "returns error if there is less than two base generators",
- baseGenerators: []v1alpha1.ApplicationSetNestedGenerator{
+ baseGenerators: []argoprojiov1alpha1.ApplicationSetNestedGenerator{
{
Git: gitGenerator,
},
@@ -298,7 +300,7 @@ func TestMatrixGenerateGoTemplate(t *testing.T) {
},
{
name: "returns error if there is more than two base generators",
- baseGenerators: []v1alpha1.ApplicationSetNestedGenerator{
+ baseGenerators: []argoprojiov1alpha1.ApplicationSetNestedGenerator{
{
List: listGenerator,
},
@@ -313,7 +315,7 @@ func TestMatrixGenerateGoTemplate(t *testing.T) {
},
{
name: "returns error if there is more than one inner generator in the first base generator",
- baseGenerators: []v1alpha1.ApplicationSetNestedGenerator{
+ baseGenerators: []argoprojiov1alpha1.ApplicationSetNestedGenerator{
{
Git: gitGenerator,
List: listGenerator,
@@ -326,7 +328,7 @@ func TestMatrixGenerateGoTemplate(t *testing.T) {
},
{
name: "returns error if there is more than one inner generator in the second base generator",
- baseGenerators: []v1alpha1.ApplicationSetNestedGenerator{
+ baseGenerators: []argoprojiov1alpha1.ApplicationSetNestedGenerator{
{
List: listGenerator,
},
@@ -344,21 +346,21 @@ func TestMatrixGenerateGoTemplate(t *testing.T) {
t.Run(testCaseCopy.name, func(t *testing.T) {
genMock := &generatorMock{}
- appSet := &v1alpha1.ApplicationSet{
+ appSet := &argoprojiov1alpha1.ApplicationSet{
ObjectMeta: metav1.ObjectMeta{
Name: "set",
},
- Spec: v1alpha1.ApplicationSetSpec{
+ Spec: argoprojiov1alpha1.ApplicationSetSpec{
GoTemplate: true,
},
}
for _, g := range testCaseCopy.baseGenerators {
- gitGeneratorSpec := v1alpha1.ApplicationSetGenerator{
+ gitGeneratorSpec := argoprojiov1alpha1.ApplicationSetGenerator{
Git: g.Git,
List: g.List,
}
- genMock.On("GenerateParams", mock.AnythingOfType("*v1alpha1.ApplicationSetGenerator"), appSet, mock.Anything).Return([]map[string]any{
+ genMock.On("GenerateParams", mock.AnythingOfType("*v1alpha1.ApplicationSetGenerator"), appSet, mock.Anything).Return([]map[string]interface{}{
{
"path": map[string]string{
"path": "app1",
@@ -376,7 +378,7 @@ func TestMatrixGenerateGoTemplate(t *testing.T) {
}, nil)
genMock.On("GetTemplate", &gitGeneratorSpec).
- Return(&v1alpha1.ApplicationSetTemplate{})
+ Return(&argoprojiov1alpha1.ApplicationSetTemplate{})
}
matrixGenerator := NewMatrixGenerator(
@@ -386,10 +388,10 @@ func TestMatrixGenerateGoTemplate(t *testing.T) {
},
)
- got, err := matrixGenerator.GenerateParams(&v1alpha1.ApplicationSetGenerator{
- Matrix: &v1alpha1.MatrixGenerator{
+ got, err := matrixGenerator.GenerateParams(&argoprojiov1alpha1.ApplicationSetGenerator{
+ Matrix: &argoprojiov1alpha1.MatrixGenerator{
Generators: testCaseCopy.baseGenerators,
- Template: v1alpha1.ApplicationSetTemplate{},
+ Template: argoprojiov1alpha1.ApplicationSetTemplate{},
},
}, appSet, nil)
@@ -404,31 +406,31 @@ func TestMatrixGenerateGoTemplate(t *testing.T) {
}
func TestMatrixGetRequeueAfter(t *testing.T) {
- gitGenerator := &v1alpha1.GitGenerator{
+ gitGenerator := &argoprojiov1alpha1.GitGenerator{
RepoURL: "RepoURL",
Revision: "Revision",
- Directories: []v1alpha1.GitDirectoryGeneratorItem{{Path: "*"}},
+ Directories: []argoprojiov1alpha1.GitDirectoryGeneratorItem{{Path: "*"}},
}
- listGenerator := &v1alpha1.ListGenerator{
+ listGenerator := &argoprojiov1alpha1.ListGenerator{
Elements: []apiextensionsv1.JSON{{Raw: []byte(`{"cluster": "Cluster","url": "Url"}`)}},
}
- pullRequestGenerator := &v1alpha1.PullRequestGenerator{}
+ pullRequestGenerator := &argoprojiov1alpha1.PullRequestGenerator{}
- scmGenerator := &v1alpha1.SCMProviderGenerator{}
+ scmGenerator := &argoprojiov1alpha1.SCMProviderGenerator{}
- duckTypeGenerator := &v1alpha1.DuckTypeGenerator{}
+ duckTypeGenerator := &argoprojiov1alpha1.DuckTypeGenerator{}
testCases := []struct {
name string
- baseGenerators []v1alpha1.ApplicationSetNestedGenerator
+ baseGenerators []argoprojiov1alpha1.ApplicationSetNestedGenerator
gitGetRequeueAfter time.Duration
expected time.Duration
}{
{
name: "return NoRequeueAfter if all the inner baseGenerators returns it",
- baseGenerators: []v1alpha1.ApplicationSetNestedGenerator{
+ baseGenerators: []argoprojiov1alpha1.ApplicationSetNestedGenerator{
{
Git: gitGenerator,
},
@@ -441,7 +443,7 @@ func TestMatrixGetRequeueAfter(t *testing.T) {
},
{
name: "returns the minimal time",
- baseGenerators: []v1alpha1.ApplicationSetNestedGenerator{
+ baseGenerators: []argoprojiov1alpha1.ApplicationSetNestedGenerator{
{
Git: gitGenerator,
},
@@ -454,7 +456,7 @@ func TestMatrixGetRequeueAfter(t *testing.T) {
},
{
name: "returns the minimal time for pull request",
- baseGenerators: []v1alpha1.ApplicationSetNestedGenerator{
+ baseGenerators: []argoprojiov1alpha1.ApplicationSetNestedGenerator{
{
Git: gitGenerator,
},
@@ -467,7 +469,7 @@ func TestMatrixGetRequeueAfter(t *testing.T) {
},
{
name: "returns the default time if no requeueAfterSeconds is provided",
- baseGenerators: []v1alpha1.ApplicationSetNestedGenerator{
+ baseGenerators: []argoprojiov1alpha1.ApplicationSetNestedGenerator{
{
Git: gitGenerator,
},
@@ -479,7 +481,7 @@ func TestMatrixGetRequeueAfter(t *testing.T) {
},
{
name: "returns the default time for duck type generator",
- baseGenerators: []v1alpha1.ApplicationSetNestedGenerator{
+ baseGenerators: []argoprojiov1alpha1.ApplicationSetNestedGenerator{
{
Git: gitGenerator,
},
@@ -491,7 +493,7 @@ func TestMatrixGetRequeueAfter(t *testing.T) {
},
{
name: "returns the default time for scm generator",
- baseGenerators: []v1alpha1.ApplicationSetNestedGenerator{
+ baseGenerators: []argoprojiov1alpha1.ApplicationSetNestedGenerator{
{
Git: gitGenerator,
},
@@ -510,7 +512,7 @@ func TestMatrixGetRequeueAfter(t *testing.T) {
mock := &generatorMock{}
for _, g := range testCaseCopy.baseGenerators {
- gitGeneratorSpec := v1alpha1.ApplicationSetGenerator{
+ gitGeneratorSpec := argoprojiov1alpha1.ApplicationSetGenerator{
Git: g.Git,
List: g.List,
PullRequest: g.PullRequest,
@@ -530,10 +532,10 @@ func TestMatrixGetRequeueAfter(t *testing.T) {
},
)
- got := matrixGenerator.GetRequeueAfter(&v1alpha1.ApplicationSetGenerator{
- Matrix: &v1alpha1.MatrixGenerator{
+ got := matrixGenerator.GetRequeueAfter(&argoprojiov1alpha1.ApplicationSetGenerator{
+ Matrix: &argoprojiov1alpha1.MatrixGenerator{
Generators: testCaseCopy.baseGenerators,
- Template: v1alpha1.ApplicationSetTemplate{},
+ Template: argoprojiov1alpha1.ApplicationSetTemplate{},
},
})
@@ -543,16 +545,16 @@ func TestMatrixGetRequeueAfter(t *testing.T) {
}
func TestInterpolatedMatrixGenerate(t *testing.T) {
- interpolatedGitGenerator := &v1alpha1.GitGenerator{
+ interpolatedGitGenerator := &argoprojiov1alpha1.GitGenerator{
RepoURL: "RepoURL",
Revision: "Revision",
- Files: []v1alpha1.GitFileGeneratorItem{
+ Files: []argoprojiov1alpha1.GitFileGeneratorItem{
{Path: "examples/git-generator-files-discovery/cluster-config/dev/config.json"},
{Path: "examples/git-generator-files-discovery/cluster-config/prod/config.json"},
},
}
- interpolatedClusterGenerator := &v1alpha1.ClusterGenerator{
+ interpolatedClusterGenerator := &argoprojiov1alpha1.ClusterGenerator{
Selector: metav1.LabelSelector{
MatchLabels: map[string]string{"environment": "{{path.basename}}"},
MatchExpressions: nil,
@@ -560,14 +562,14 @@ func TestInterpolatedMatrixGenerate(t *testing.T) {
}
testCases := []struct {
name string
- baseGenerators []v1alpha1.ApplicationSetNestedGenerator
+ baseGenerators []argoprojiov1alpha1.ApplicationSetNestedGenerator
expectedErr error
- expected []map[string]any
+ expected []map[string]interface{}
clientError bool
}{
{
name: "happy flow - generate interpolated params",
- baseGenerators: []v1alpha1.ApplicationSetNestedGenerator{
+ baseGenerators: []argoprojiov1alpha1.ApplicationSetNestedGenerator{
{
Git: interpolatedGitGenerator,
},
@@ -575,7 +577,7 @@ func TestInterpolatedMatrixGenerate(t *testing.T) {
Clusters: interpolatedClusterGenerator,
},
},
- expected: []map[string]any{
+ expected: []map[string]interface{}{
{"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": ""},
},
@@ -635,7 +637,7 @@ func TestInterpolatedMatrixGenerate(t *testing.T) {
t.Run(testCaseCopy.name, func(t *testing.T) {
genMock := &generatorMock{}
- appSet := &v1alpha1.ApplicationSet{}
+ appSet := &argoprojiov1alpha1.ApplicationSet{}
appClientset := kubefake.NewSimpleClientset(runtimeClusters...)
fakeClient := fake.NewClientBuilder().WithObjects(clusters...).Build()
@@ -643,14 +645,14 @@ func TestInterpolatedMatrixGenerate(t *testing.T) {
fakeClient,
testCase.clientError,
}
- clusterGenerator := NewClusterGenerator(t.Context(), cl, appClientset, "namespace")
+ clusterGenerator := NewClusterGenerator(cl, context.Background(), appClientset, "namespace")
for _, g := range testCaseCopy.baseGenerators {
- gitGeneratorSpec := v1alpha1.ApplicationSetGenerator{
+ gitGeneratorSpec := argoprojiov1alpha1.ApplicationSetGenerator{
Git: g.Git,
Clusters: g.Clusters,
}
- genMock.On("GenerateParams", mock.AnythingOfType("*v1alpha1.ApplicationSetGenerator"), appSet).Return([]map[string]any{
+ genMock.On("GenerateParams", mock.AnythingOfType("*v1alpha1.ApplicationSetGenerator"), appSet).Return([]map[string]interface{}{
{
"path": "examples/git-generator-files-discovery/cluster-config/dev/config.json",
"path.basename": "dev",
@@ -663,7 +665,7 @@ func TestInterpolatedMatrixGenerate(t *testing.T) {
},
}, nil)
genMock.On("GetTemplate", &gitGeneratorSpec).
- Return(&v1alpha1.ApplicationSetTemplate{})
+ Return(&argoprojiov1alpha1.ApplicationSetTemplate{})
}
matrixGenerator := NewMatrixGenerator(
map[string]Generator{
@@ -672,10 +674,10 @@ func TestInterpolatedMatrixGenerate(t *testing.T) {
},
)
- got, err := matrixGenerator.GenerateParams(&v1alpha1.ApplicationSetGenerator{
- Matrix: &v1alpha1.MatrixGenerator{
+ got, err := matrixGenerator.GenerateParams(&argoprojiov1alpha1.ApplicationSetGenerator{
+ Matrix: &argoprojiov1alpha1.MatrixGenerator{
Generators: testCaseCopy.baseGenerators,
- Template: v1alpha1.ApplicationSetTemplate{},
+ Template: argoprojiov1alpha1.ApplicationSetTemplate{},
},
}, appSet, nil)
@@ -690,16 +692,16 @@ func TestInterpolatedMatrixGenerate(t *testing.T) {
}
func TestInterpolatedMatrixGenerateGoTemplate(t *testing.T) {
- interpolatedGitGenerator := &v1alpha1.GitGenerator{
+ interpolatedGitGenerator := &argoprojiov1alpha1.GitGenerator{
RepoURL: "RepoURL",
Revision: "Revision",
- Files: []v1alpha1.GitFileGeneratorItem{
+ Files: []argoprojiov1alpha1.GitFileGeneratorItem{
{Path: "examples/git-generator-files-discovery/cluster-config/dev/config.json"},
{Path: "examples/git-generator-files-discovery/cluster-config/prod/config.json"},
},
}
- interpolatedClusterGenerator := &v1alpha1.ClusterGenerator{
+ interpolatedClusterGenerator := &argoprojiov1alpha1.ClusterGenerator{
Selector: metav1.LabelSelector{
MatchLabels: map[string]string{"environment": "{{.path.basename}}"},
MatchExpressions: nil,
@@ -707,14 +709,14 @@ func TestInterpolatedMatrixGenerateGoTemplate(t *testing.T) {
}
testCases := []struct {
name string
- baseGenerators []v1alpha1.ApplicationSetNestedGenerator
+ baseGenerators []argoprojiov1alpha1.ApplicationSetNestedGenerator
expectedErr error
- expected []map[string]any
+ expected []map[string]interface{}
clientError bool
}{
{
name: "happy flow - generate interpolated params",
- baseGenerators: []v1alpha1.ApplicationSetNestedGenerator{
+ baseGenerators: []argoprojiov1alpha1.ApplicationSetNestedGenerator{
{
Git: interpolatedGitGenerator,
},
@@ -722,7 +724,7 @@ func TestInterpolatedMatrixGenerateGoTemplate(t *testing.T) {
Clusters: interpolatedClusterGenerator,
},
},
- expected: []map[string]any{
+ expected: []map[string]interface{}{
{
"path": map[string]string{
"path": "examples/git-generator-files-discovery/cluster-config/dev/config.json",
@@ -733,7 +735,7 @@ func TestInterpolatedMatrixGenerateGoTemplate(t *testing.T) {
"nameNormalized": "dev-01",
"server": "https://dev-01.example.com",
"project": "",
- "metadata": map[string]any{
+ "metadata": map[string]interface{}{
"labels": map[string]string{
"environment": "dev",
"argocd.argoproj.io/secret-type": "cluster",
@@ -750,7 +752,7 @@ func TestInterpolatedMatrixGenerateGoTemplate(t *testing.T) {
"nameNormalized": "prod-01",
"server": "https://prod-01.example.com",
"project": "",
- "metadata": map[string]any{
+ "metadata": map[string]interface{}{
"labels": map[string]string{
"environment": "prod",
"argocd.argoproj.io/secret-type": "cluster",
@@ -814,8 +816,8 @@ func TestInterpolatedMatrixGenerateGoTemplate(t *testing.T) {
t.Run(testCaseCopy.name, func(t *testing.T) {
genMock := &generatorMock{}
- appSet := &v1alpha1.ApplicationSet{
- Spec: v1alpha1.ApplicationSetSpec{
+ appSet := &argoprojiov1alpha1.ApplicationSet{
+ Spec: argoprojiov1alpha1.ApplicationSetSpec{
GoTemplate: true,
},
}
@@ -826,14 +828,14 @@ func TestInterpolatedMatrixGenerateGoTemplate(t *testing.T) {
fakeClient,
testCase.clientError,
}
- clusterGenerator := NewClusterGenerator(t.Context(), cl, appClientset, "namespace")
+ clusterGenerator := NewClusterGenerator(cl, context.Background(), appClientset, "namespace")
for _, g := range testCaseCopy.baseGenerators {
- gitGeneratorSpec := v1alpha1.ApplicationSetGenerator{
+ gitGeneratorSpec := argoprojiov1alpha1.ApplicationSetGenerator{
Git: g.Git,
Clusters: g.Clusters,
}
- genMock.On("GenerateParams", mock.AnythingOfType("*v1alpha1.ApplicationSetGenerator"), appSet).Return([]map[string]any{
+ genMock.On("GenerateParams", mock.AnythingOfType("*v1alpha1.ApplicationSetGenerator"), appSet).Return([]map[string]interface{}{
{
"path": map[string]string{
"path": "examples/git-generator-files-discovery/cluster-config/dev/config.json",
@@ -850,7 +852,7 @@ func TestInterpolatedMatrixGenerateGoTemplate(t *testing.T) {
},
}, nil)
genMock.On("GetTemplate", &gitGeneratorSpec).
- Return(&v1alpha1.ApplicationSetTemplate{})
+ Return(&argoprojiov1alpha1.ApplicationSetTemplate{})
}
matrixGenerator := NewMatrixGenerator(
map[string]Generator{
@@ -859,10 +861,10 @@ func TestInterpolatedMatrixGenerateGoTemplate(t *testing.T) {
},
)
- got, err := matrixGenerator.GenerateParams(&v1alpha1.ApplicationSetGenerator{
- Matrix: &v1alpha1.MatrixGenerator{
+ got, err := matrixGenerator.GenerateParams(&argoprojiov1alpha1.ApplicationSetGenerator{
+ Matrix: &argoprojiov1alpha1.MatrixGenerator{
Generators: testCaseCopy.baseGenerators,
- Template: v1alpha1.ApplicationSetTemplate{},
+ Template: argoprojiov1alpha1.ApplicationSetTemplate{},
},
}, appSet, nil)
@@ -877,28 +879,28 @@ func TestInterpolatedMatrixGenerateGoTemplate(t *testing.T) {
}
func TestMatrixGenerateListElementsYaml(t *testing.T) {
- gitGenerator := &v1alpha1.GitGenerator{
+ gitGenerator := &argoprojiov1alpha1.GitGenerator{
RepoURL: "RepoURL",
Revision: "Revision",
- Files: []v1alpha1.GitFileGeneratorItem{
+ Files: []argoprojiov1alpha1.GitFileGeneratorItem{
{Path: "config.yaml"},
},
}
- listGenerator := &v1alpha1.ListGenerator{
+ listGenerator := &argoprojiov1alpha1.ListGenerator{
Elements: []apiextensionsv1.JSON{},
ElementsYaml: "{{ .foo.bar | toJson }}",
}
testCases := []struct {
name string
- baseGenerators []v1alpha1.ApplicationSetNestedGenerator
+ baseGenerators []argoprojiov1alpha1.ApplicationSetNestedGenerator
expectedErr error
- expected []map[string]any
+ expected []map[string]interface{}
}{
{
name: "happy flow - generate params",
- baseGenerators: []v1alpha1.ApplicationSetNestedGenerator{
+ baseGenerators: []argoprojiov1alpha1.ApplicationSetNestedGenerator{
{
Git: gitGenerator,
},
@@ -906,23 +908,23 @@ func TestMatrixGenerateListElementsYaml(t *testing.T) {
List: listGenerator,
},
},
- expected: []map[string]any{
+ expected: []map[string]interface{}{
{
"chart": "a",
"version": "1",
- "foo": map[string]any{
- "bar": []any{
- map[string]any{
+ "foo": map[string]interface{}{
+ "bar": []interface{}{
+ map[string]interface{}{
"chart": "a",
"version": "1",
},
- map[string]any{
+ map[string]interface{}{
"chart": "b",
"version": "2",
},
},
},
- "path": map[string]any{
+ "path": map[string]interface{}{
"basename": "dir",
"basenameNormalized": "dir",
"filename": "file_name.yaml",
@@ -937,19 +939,19 @@ func TestMatrixGenerateListElementsYaml(t *testing.T) {
{
"chart": "b",
"version": "2",
- "foo": map[string]any{
- "bar": []any{
- map[string]any{
+ "foo": map[string]interface{}{
+ "bar": []interface{}{
+ map[string]interface{}{
"chart": "a",
"version": "1",
},
- map[string]any{
+ map[string]interface{}{
"chart": "b",
"version": "2",
},
},
},
- "path": map[string]any{
+ "path": map[string]interface{}{
"basename": "dir",
"basenameNormalized": "dir",
"filename": "file_name.yaml",
@@ -970,34 +972,34 @@ func TestMatrixGenerateListElementsYaml(t *testing.T) {
t.Run(testCaseCopy.name, func(t *testing.T) {
genMock := &generatorMock{}
- appSet := &v1alpha1.ApplicationSet{
+ appSet := &argoprojiov1alpha1.ApplicationSet{
ObjectMeta: metav1.ObjectMeta{
Name: "set",
},
- Spec: v1alpha1.ApplicationSetSpec{
+ Spec: argoprojiov1alpha1.ApplicationSetSpec{
GoTemplate: true,
},
}
for _, g := range testCaseCopy.baseGenerators {
- gitGeneratorSpec := v1alpha1.ApplicationSetGenerator{
+ gitGeneratorSpec := argoprojiov1alpha1.ApplicationSetGenerator{
Git: g.Git,
List: g.List,
}
genMock.On("GenerateParams", mock.AnythingOfType("*v1alpha1.ApplicationSetGenerator"), appSet).Return([]map[string]any{{
- "foo": map[string]any{
- "bar": []any{
- map[string]any{
+ "foo": map[string]interface{}{
+ "bar": []interface{}{
+ map[string]interface{}{
"chart": "a",
"version": "1",
},
- map[string]any{
+ map[string]interface{}{
"chart": "b",
"version": "2",
},
},
},
- "path": map[string]any{
+ "path": map[string]interface{}{
"basename": "dir",
"basenameNormalized": "dir",
"filename": "file_name.yaml",
@@ -1010,7 +1012,7 @@ func TestMatrixGenerateListElementsYaml(t *testing.T) {
},
}}, nil)
genMock.On("GetTemplate", &gitGeneratorSpec).
- Return(&v1alpha1.ApplicationSetTemplate{})
+ Return(&argoprojiov1alpha1.ApplicationSetTemplate{})
}
matrixGenerator := NewMatrixGenerator(
@@ -1020,10 +1022,10 @@ func TestMatrixGenerateListElementsYaml(t *testing.T) {
},
)
- got, err := matrixGenerator.GenerateParams(&v1alpha1.ApplicationSetGenerator{
- Matrix: &v1alpha1.MatrixGenerator{
+ got, err := matrixGenerator.GenerateParams(&argoprojiov1alpha1.ApplicationSetGenerator{
+ Matrix: &argoprojiov1alpha1.MatrixGenerator{
Generators: testCaseCopy.baseGenerators,
- Template: v1alpha1.ApplicationSetTemplate{},
+ Template: argoprojiov1alpha1.ApplicationSetTemplate{},
},
}, appSet, nil)
@@ -1041,19 +1043,19 @@ type generatorMock struct {
mock.Mock
}
-func (g *generatorMock) GetTemplate(appSetGenerator *v1alpha1.ApplicationSetGenerator) *v1alpha1.ApplicationSetTemplate {
+func (g *generatorMock) GetTemplate(appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator) *argoprojiov1alpha1.ApplicationSetTemplate {
args := g.Called(appSetGenerator)
- return args.Get(0).(*v1alpha1.ApplicationSetTemplate)
+ return args.Get(0).(*argoprojiov1alpha1.ApplicationSetTemplate)
}
-func (g *generatorMock) GenerateParams(appSetGenerator *v1alpha1.ApplicationSetGenerator, appSet *v1alpha1.ApplicationSet, _ client.Client) ([]map[string]any, error) {
+func (g *generatorMock) GenerateParams(appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator, appSet *argoprojiov1alpha1.ApplicationSet, _ client.Client) ([]map[string]interface{}, error) {
args := g.Called(appSetGenerator, appSet)
- return args.Get(0).([]map[string]any), args.Error(1)
+ return args.Get(0).([]map[string]interface{}), args.Error(1)
}
-func (g *generatorMock) GetRequeueAfter(appSetGenerator *v1alpha1.ApplicationSetGenerator) time.Duration {
+func (g *generatorMock) GetRequeueAfter(appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator) time.Duration {
args := g.Called(appSetGenerator)
return args.Get(0).(time.Duration)
@@ -1073,20 +1075,20 @@ 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]any{
+ listGeneratorMock.On("GenerateParams", mock.AnythingOfType("*v1alpha1.ApplicationSetGenerator"), mock.AnythingOfType("*v1alpha1.ApplicationSet"), mock.Anything).Return([]map[string]interface{}{
{"some": "value"},
}, nil)
- listGeneratorMock.On("GetTemplate", mock.AnythingOfType("*v1alpha1.ApplicationSetGenerator")).Return(&v1alpha1.ApplicationSetTemplate{})
+ listGeneratorMock.On("GetTemplate", mock.AnythingOfType("*v1alpha1.ApplicationSetGenerator")).Return(&argoprojiov1alpha1.ApplicationSetTemplate{})
- gitGeneratorSpec := &v1alpha1.GitGenerator{
+ gitGeneratorSpec := &argoprojiov1alpha1.GitGenerator{
RepoURL: "https://git.example.com",
- Files: []v1alpha1.GitFileGeneratorItem{
+ Files: []argoprojiov1alpha1.GitFileGeneratorItem{
{Path: "some/path.json"},
},
}
repoServiceMock := &mocks.Repos{}
- repoServiceMock.On("GetFiles", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(map[string][]byte{
+ repoServiceMock.On("GetFiles", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(map[string][]byte{
"some/path.json": []byte("test: content"),
}, nil)
gitGenerator := NewGitGenerator(repoServiceMock, "")
@@ -1096,10 +1098,10 @@ func TestGitGenerator_GenerateParams_list_x_git_matrix_generator(t *testing.T) {
"Git": gitGenerator,
})
- matrixGeneratorSpec := &v1alpha1.MatrixGenerator{
- Generators: []v1alpha1.ApplicationSetNestedGenerator{
+ matrixGeneratorSpec := &argoprojiov1alpha1.MatrixGenerator{
+ Generators: []argoprojiov1alpha1.ApplicationSetNestedGenerator{
{
- List: &v1alpha1.ListGenerator{
+ List: &argoprojiov1alpha1.ListGenerator{
Elements: []apiextensionsv1.JSON{
{
Raw: []byte(`{"some": "value"}`),
@@ -1116,15 +1118,15 @@ func TestGitGenerator_GenerateParams_list_x_git_matrix_generator(t *testing.T) {
scheme := runtime.NewScheme()
err := v1alpha1.AddToScheme(scheme)
require.NoError(t, err)
- appProject := v1alpha1.AppProject{}
+ appProject := argoprojiov1alpha1.AppProject{}
client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(&appProject).Build()
- params, err := matrixGenerator.GenerateParams(&v1alpha1.ApplicationSetGenerator{
+ params, err := matrixGenerator.GenerateParams(&argoprojiov1alpha1.ApplicationSetGenerator{
Matrix: matrixGeneratorSpec,
- }, &v1alpha1.ApplicationSet{}, client)
+ }, &argoprojiov1alpha1.ApplicationSet{}, client)
require.NoError(t, err)
- assert.Equal(t, []map[string]any{{
+ assert.Equal(t, []map[string]interface{}{{
"path": "some",
"path.basename": "some",
"path.basenameNormalized": "some",
diff --git a/applicationset/generators/merge.go b/applicationset/generators/merge.go
index a88af3543a..e9af81fada 100644
--- a/applicationset/generators/merge.go
+++ b/applicationset/generators/merge.go
@@ -2,23 +2,24 @@ package generators
import (
"encoding/json"
- "errors"
"fmt"
"time"
- "dario.cat/mergo"
+ "github.com/imdario/mergo"
"sigs.k8s.io/controller-runtime/pkg/client"
- "github.com/argoproj/argo-cd/v3/applicationset/utils"
- argoprojiov1alpha1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/applicationset/utils"
+ argoprojiov1alpha1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+
+ log "github.com/sirupsen/logrus"
)
var _ Generator = (*MergeGenerator)(nil)
var (
- ErrLessThanTwoGeneratorsInMerge = errors.New("found less than two generators, Merge requires two or more")
- ErrNoMergeKeys = errors.New("no merge keys were specified, Merge requires at least one")
- ErrNonUniqueParamSets = errors.New("the parameters from a generator were not unique by the given mergeKeys, Merge requires all param sets to be unique")
+ ErrLessThanTwoGeneratorsInMerge = fmt.Errorf("found less than two generators, Merge requires two or more")
+ ErrNoMergeKeys = fmt.Errorf("no merge keys were specified, Merge requires at least one")
+ ErrNonUniqueParamSets = fmt.Errorf("the parameters from a generator were not unique by the given mergeKeys, Merge requires all param sets to be unique")
)
type MergeGenerator struct {
@@ -36,8 +37,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]any, error) {
- var paramSets [][]map[string]any
+func (m *MergeGenerator) getParamSetsForAllGenerators(generators []argoprojiov1alpha1.ApplicationSetNestedGenerator, appSet *argoprojiov1alpha1.ApplicationSet, client client.Client) ([][]map[string]interface{}, error) {
+ var paramSets [][]map[string]interface{}
for i, generator := range generators {
generatorParamSets, err := m.getParams(generator, appSet, client)
if err != nil {
@@ -50,9 +51,9 @@ 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]any, error) {
+func (m *MergeGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator, appSet *argoprojiov1alpha1.ApplicationSet, client client.Client) ([]map[string]interface{}, error) {
if appSetGenerator.Merge == nil {
- return nil, ErrEmptyAppSetGenerator
+ return nil, EmptyAppSetGeneratorError
}
if len(appSetGenerator.Merge.Generators) < 2 {
@@ -93,11 +94,11 @@ func (m *MergeGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha1.Appl
}
}
- mergedParamSets := make([]map[string]any, len(baseParamSetsByMergeKey))
+ mergedParamSets := make([]map[string]interface{}, len(baseParamSetsByMergeKey))
i := 0
for _, mergedParamSet := range baseParamSetsByMergeKey {
mergedParamSets[i] = mergedParamSet
- i++
+ i += 1
}
return mergedParamSets, nil
@@ -106,7 +107,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]any) (map[string]map[string]any, error) {
+func getParamSetsByMergeKey(mergeKeys []string, paramSets []map[string]interface{}) (map[string]map[string]interface{}, error) {
if len(mergeKeys) < 1 {
return nil, ErrNoMergeKeys
}
@@ -116,17 +117,17 @@ func getParamSetsByMergeKey(mergeKeys []string, paramSets []map[string]any) (map
deDuplicatedMergeKeys[mergeKey] = false
}
- paramSetsByMergeKey := make(map[string]map[string]any, len(paramSets))
+ paramSetsByMergeKey := make(map[string]map[string]interface{}, len(paramSets))
for _, paramSet := range paramSets {
- paramSetKey := make(map[string]any)
+ paramSetKey := make(map[string]interface{})
for mergeKey := range deDuplicatedMergeKeys {
paramSetKey[mergeKey] = paramSet[mergeKey]
}
- paramSetKeyJSON, err := json.Marshal(paramSetKey)
+ paramSetKeyJson, err := json.Marshal(paramSetKey)
if err != nil {
return nil, fmt.Errorf("error marshalling param set key json: %w", err)
}
- paramSetKeyString := string(paramSetKeyJSON)
+ paramSetKeyString := string(paramSetKeyJson)
if _, exists := paramSetsByMergeKey[paramSetKeyString]; exists {
return nil, fmt.Errorf("%w. Duplicate key was %s", ErrNonUniqueParamSets, paramSetKeyString)
}
@@ -137,15 +138,27 @@ func getParamSetsByMergeKey(mergeKeys []string, paramSets []map[string]any) (map
}
// getParams get the parameters generated by this generator.
-func (m *MergeGenerator) getParams(appSetBaseGenerator argoprojiov1alpha1.ApplicationSetNestedGenerator, appSet *argoprojiov1alpha1.ApplicationSet, client client.Client) ([]map[string]any, error) {
+func (m *MergeGenerator) getParams(appSetBaseGenerator argoprojiov1alpha1.ApplicationSetNestedGenerator, appSet *argoprojiov1alpha1.ApplicationSet, client client.Client) ([]map[string]interface{}, error) {
matrixGen, err := getMatrixGenerator(appSetBaseGenerator)
if err != nil {
return nil, err
}
+ if matrixGen != nil && !appSet.Spec.ApplyNestedSelectors {
+ foundSelector := dropDisabledNestedSelectors(matrixGen.Generators)
+ if foundSelector {
+ log.Warnf("AppSet '%v' defines selector on nested matrix generator's generator without enabling them via 'spec.applyNestedSelectors', ignoring nested selector", appSet.Name)
+ }
+ }
mergeGen, err := getMergeGenerator(appSetBaseGenerator)
if err != nil {
return nil, err
}
+ if mergeGen != nil && !appSet.Spec.ApplyNestedSelectors {
+ foundSelector := dropDisabledNestedSelectors(mergeGen.Generators)
+ if foundSelector {
+ log.Warnf("AppSet '%v' defines selector on nested merge generator's generator without enabling them via 'spec.applyNestedSelectors', ignoring nested selector", appSet.Name)
+ }
+ }
t, err := Transform(
argoprojiov1alpha1.ApplicationSetGenerator{
@@ -163,13 +176,13 @@ func (m *MergeGenerator) getParams(appSetBaseGenerator argoprojiov1alpha1.Applic
m.supportedGenerators,
argoprojiov1alpha1.ApplicationSetTemplate{},
appSet,
- map[string]any{}, client)
+ map[string]interface{}{}, client)
if err != nil {
return nil, fmt.Errorf("child generator returned an error on parameter generation: %w", err)
}
if len(t) == 0 {
- return nil, errors.New("child generator generated no parameters")
+ return nil, fmt.Errorf("child generator generated no parameters")
}
if len(t) > 1 {
@@ -210,8 +223,9 @@ 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/merge_test.go b/applicationset/generators/merge_test.go
index 0bb2bfbce7..ad54debb37 100644
--- a/applicationset/generators/merge_test.go
+++ b/applicationset/generators/merge_test.go
@@ -9,7 +9,7 @@ import (
"github.com/stretchr/testify/require"
apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
- argoprojiov1alpha1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ argoprojiov1alpha1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
)
func getNestedListGenerator(json string) *argoprojiov1alpha1.ApplicationSetNestedGenerator {
@@ -36,15 +36,15 @@ func getTerminalListGeneratorMultiple(jsons []string) argoprojiov1alpha1.Applica
return generator
}
-func listOfMapsToSet(maps []map[string]any) (map[string]bool, error) {
+func listOfMapsToSet(maps []map[string]interface{}) (map[string]bool, error) {
set := make(map[string]bool, len(maps))
for _, paramMap := range maps {
- paramMapAsJSON, err := json.Marshal(paramMap)
+ paramMapAsJson, err := json.Marshal(paramMap)
if err != nil {
return nil, err
}
- set[string(paramMapAsJSON)] = false
+ set[string(paramMapAsJson)] = false
}
return set, nil
}
@@ -55,7 +55,7 @@ func TestMergeGenerate(t *testing.T) {
baseGenerators []argoprojiov1alpha1.ApplicationSetNestedGenerator
mergeKeys []string
expectedErr error
- expected []map[string]any
+ expected []map[string]interface{}
}{
{
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]any{
+ expected: []map[string]interface{}{
{"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]any{
+ expected: []map[string]interface{}{
{"a": "a"},
},
},
@@ -101,7 +101,7 @@ func TestMergeGenerate(t *testing.T) {
*getNestedListGenerator(`{"b": "b"}`),
},
mergeKeys: []string{"b"},
- expected: []map[string]any{
+ expected: []map[string]interface{}{
{"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]any{
+ expected: []map[string]interface{}{
{"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]any{
+ expected: []map[string]interface{}{
{"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 any) *apiextensionsv1.JSON {
+func toAPIExtensionsJSON(t *testing.T, g interface{}) *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]any
+ paramSets []map[string]interface{}
expectedErr error
- expected map[string]map[string]any
+ expected map[string]map[string]interface{}
}{
{
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]any),
+ expected: make(map[string]map[string]interface{}),
},
{
name: "simple key, unique paramSets",
mergeKeys: []string{"key"},
- paramSets: []map[string]any{{"key": "a"}, {"key": "b"}},
- expected: map[string]map[string]any{
+ paramSets: []map[string]interface{}{{"key": "a"}, {"key": "b"}},
+ expected: map[string]map[string]interface{}{
`{"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]any{{"key": map[string]any{"hello": "world"}}, {"key": "b"}},
- expected: map[string]map[string]any{
- `{"key":{"hello":"world"}}`: {"key": map[string]any{"hello": "world"}},
+ 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"}},
`{"key":"b"}`: {"key": "b"},
},
},
{
name: "simple key, non-unique paramSets",
mergeKeys: []string{"key"},
- paramSets: []map[string]any{{"key": "a"}, {"key": "b"}, {"key": "b"}},
+ paramSets: []map[string]interface{}{{"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]any{{"key": "a"}, {"key": "b"}},
- expected: map[string]map[string]any{
+ paramSets: []map[string]interface{}{{"key": "a"}, {"key": "b"}},
+ expected: map[string]map[string]interface{}{
`{"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]any{{"key": "a"}, {"key": "b"}, {"key": "b"}},
+ paramSets: []map[string]interface{}{{"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]any{
+ paramSets: []map[string]interface{}{
{"key1": "a", "key2": "a"},
{"key1": "a", "key2": "b"},
{"key1": "b", "key2": "a"},
},
- expected: map[string]map[string]any{
+ expected: map[string]map[string]interface{}{
`{"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]any{
- {"key1": "a", "key2": map[string]any{"hello": "world"}},
+ paramSets: []map[string]interface{}{
+ {"key1": "a", "key2": map[string]interface{}{"hello": "world"}},
{"key1": "a", "key2": "b"},
{"key1": "b", "key2": "a"},
},
- expected: map[string]map[string]any{
- `{"key1":"a","key2":{"hello":"world"}}`: {"key1": "a", "key2": map[string]any{"hello": "world"}},
+ expected: map[string]map[string]interface{}{
+ `{"key1":"a","key2":{"hello":"world"}}`: {"key1": "a", "key2": map[string]interface{}{"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]any{
+ paramSets: []map[string]interface{}{
{"key1": "a", "key2": "a"},
{"key1": "a", "key2": "b"},
{"key1": "b", "key2": "a"},
},
- expected: map[string]map[string]any{
+ expected: map[string]map[string]interface{}{
`{"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]any{
+ paramSets: []map[string]interface{}{
{"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]any{
+ paramSets: []map[string]interface{}{
{"key1": "a", "key2": "a"},
{"key1": "a", "key2": "a"},
{"key1": "b", "key2": "a"},
diff --git a/applicationset/generators/mocks/Generator.go b/applicationset/generators/mocks/Generator.go
index 712a9ed0ed..12c153985d 100644
--- a/applicationset/generators/mocks/Generator.go
+++ b/applicationset/generators/mocks/Generator.go
@@ -1,17 +1,90 @@
-// Code generated by mockery; DO NOT EDIT.
-// github.com/vektra/mockery
-// template: testify
+// Code generated by mockery v2.53.4. DO NOT EDIT.
package mocks
import (
- "time"
+ client "sigs.k8s.io/controller-runtime/pkg/client"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
mock "github.com/stretchr/testify/mock"
- "sigs.k8s.io/controller-runtime/pkg/client"
+
+ time "time"
+
+ v1alpha1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
)
+// Generator is an autogenerated mock type for the Generator type
+type Generator struct {
+ mock.Mock
+}
+
+// GenerateParams provides a mock function with given fields: appSetGenerator, applicationSetInfo, _a2
+func (_m *Generator) GenerateParams(appSetGenerator *v1alpha1.ApplicationSetGenerator, applicationSetInfo *v1alpha1.ApplicationSet, _a2 client.Client) ([]map[string]interface{}, error) {
+ ret := _m.Called(appSetGenerator, applicationSetInfo, _a2)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GenerateParams")
+ }
+
+ var r0 []map[string]interface{}
+ var r1 error
+ if rf, ok := ret.Get(0).(func(*v1alpha1.ApplicationSetGenerator, *v1alpha1.ApplicationSet, client.Client) ([]map[string]interface{}, error)); ok {
+ return rf(appSetGenerator, applicationSetInfo, _a2)
+ }
+ if rf, ok := ret.Get(0).(func(*v1alpha1.ApplicationSetGenerator, *v1alpha1.ApplicationSet, client.Client) []map[string]interface{}); ok {
+ r0 = rf(appSetGenerator, applicationSetInfo, _a2)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).([]map[string]interface{})
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(*v1alpha1.ApplicationSetGenerator, *v1alpha1.ApplicationSet, client.Client) error); ok {
+ r1 = rf(appSetGenerator, applicationSetInfo, _a2)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetRequeueAfter provides a mock function with given fields: appSetGenerator
+func (_m *Generator) GetRequeueAfter(appSetGenerator *v1alpha1.ApplicationSetGenerator) time.Duration {
+ ret := _m.Called(appSetGenerator)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetRequeueAfter")
+ }
+
+ var r0 time.Duration
+ if rf, ok := ret.Get(0).(func(*v1alpha1.ApplicationSetGenerator) time.Duration); ok {
+ r0 = rf(appSetGenerator)
+ } else {
+ r0 = ret.Get(0).(time.Duration)
+ }
+
+ return r0
+}
+
+// GetTemplate provides a mock function with given fields: appSetGenerator
+func (_m *Generator) GetTemplate(appSetGenerator *v1alpha1.ApplicationSetGenerator) *v1alpha1.ApplicationSetTemplate {
+ ret := _m.Called(appSetGenerator)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetTemplate")
+ }
+
+ var r0 *v1alpha1.ApplicationSetTemplate
+ if rf, ok := ret.Get(0).(func(*v1alpha1.ApplicationSetGenerator) *v1alpha1.ApplicationSetTemplate); ok {
+ r0 = rf(appSetGenerator)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*v1alpha1.ApplicationSetTemplate)
+ }
+ }
+
+ return r0
+}
+
// NewGenerator creates a new instance of Generator. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
// The first argument is typically a *testing.T value.
func NewGenerator(t interface {
@@ -25,166 +98,3 @@ func NewGenerator(t interface {
return mock
}
-
-// Generator is an autogenerated mock type for the Generator type
-type Generator struct {
- mock.Mock
-}
-
-type Generator_Expecter struct {
- mock *mock.Mock
-}
-
-func (_m *Generator) EXPECT() *Generator_Expecter {
- return &Generator_Expecter{mock: &_m.Mock}
-}
-
-// GenerateParams provides a mock function for the type Generator
-func (_mock *Generator) GenerateParams(appSetGenerator *v1alpha1.ApplicationSetGenerator, applicationSetInfo *v1alpha1.ApplicationSet, client1 client.Client) ([]map[string]any, error) {
- ret := _mock.Called(appSetGenerator, applicationSetInfo, client1)
-
- if len(ret) == 0 {
- panic("no return value specified for GenerateParams")
- }
-
- var r0 []map[string]any
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(*v1alpha1.ApplicationSetGenerator, *v1alpha1.ApplicationSet, client.Client) ([]map[string]any, error)); ok {
- return returnFunc(appSetGenerator, applicationSetInfo, client1)
- }
- if returnFunc, ok := ret.Get(0).(func(*v1alpha1.ApplicationSetGenerator, *v1alpha1.ApplicationSet, client.Client) []map[string]any); ok {
- r0 = returnFunc(appSetGenerator, applicationSetInfo, client1)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).([]map[string]any)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(*v1alpha1.ApplicationSetGenerator, *v1alpha1.ApplicationSet, client.Client) error); ok {
- r1 = returnFunc(appSetGenerator, applicationSetInfo, client1)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Generator_GenerateParams_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GenerateParams'
-type Generator_GenerateParams_Call struct {
- *mock.Call
-}
-
-// GenerateParams is a helper method to define mock.On call
-// - appSetGenerator
-// - applicationSetInfo
-// - client1
-func (_e *Generator_Expecter) GenerateParams(appSetGenerator interface{}, applicationSetInfo interface{}, client1 interface{}) *Generator_GenerateParams_Call {
- return &Generator_GenerateParams_Call{Call: _e.mock.On("GenerateParams", appSetGenerator, applicationSetInfo, client1)}
-}
-
-func (_c *Generator_GenerateParams_Call) Run(run func(appSetGenerator *v1alpha1.ApplicationSetGenerator, applicationSetInfo *v1alpha1.ApplicationSet, client1 client.Client)) *Generator_GenerateParams_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(*v1alpha1.ApplicationSetGenerator), args[1].(*v1alpha1.ApplicationSet), args[2].(client.Client))
- })
- return _c
-}
-
-func (_c *Generator_GenerateParams_Call) Return(stringToVs []map[string]any, err error) *Generator_GenerateParams_Call {
- _c.Call.Return(stringToVs, err)
- return _c
-}
-
-func (_c *Generator_GenerateParams_Call) RunAndReturn(run func(appSetGenerator *v1alpha1.ApplicationSetGenerator, applicationSetInfo *v1alpha1.ApplicationSet, client1 client.Client) ([]map[string]any, error)) *Generator_GenerateParams_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetRequeueAfter provides a mock function for the type Generator
-func (_mock *Generator) GetRequeueAfter(appSetGenerator *v1alpha1.ApplicationSetGenerator) time.Duration {
- ret := _mock.Called(appSetGenerator)
-
- if len(ret) == 0 {
- panic("no return value specified for GetRequeueAfter")
- }
-
- var r0 time.Duration
- if returnFunc, ok := ret.Get(0).(func(*v1alpha1.ApplicationSetGenerator) time.Duration); ok {
- r0 = returnFunc(appSetGenerator)
- } else {
- r0 = ret.Get(0).(time.Duration)
- }
- return r0
-}
-
-// Generator_GetRequeueAfter_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetRequeueAfter'
-type Generator_GetRequeueAfter_Call struct {
- *mock.Call
-}
-
-// GetRequeueAfter is a helper method to define mock.On call
-// - appSetGenerator
-func (_e *Generator_Expecter) GetRequeueAfter(appSetGenerator interface{}) *Generator_GetRequeueAfter_Call {
- return &Generator_GetRequeueAfter_Call{Call: _e.mock.On("GetRequeueAfter", appSetGenerator)}
-}
-
-func (_c *Generator_GetRequeueAfter_Call) Run(run func(appSetGenerator *v1alpha1.ApplicationSetGenerator)) *Generator_GetRequeueAfter_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(*v1alpha1.ApplicationSetGenerator))
- })
- return _c
-}
-
-func (_c *Generator_GetRequeueAfter_Call) Return(duration time.Duration) *Generator_GetRequeueAfter_Call {
- _c.Call.Return(duration)
- return _c
-}
-
-func (_c *Generator_GetRequeueAfter_Call) RunAndReturn(run func(appSetGenerator *v1alpha1.ApplicationSetGenerator) time.Duration) *Generator_GetRequeueAfter_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetTemplate provides a mock function for the type Generator
-func (_mock *Generator) GetTemplate(appSetGenerator *v1alpha1.ApplicationSetGenerator) *v1alpha1.ApplicationSetTemplate {
- ret := _mock.Called(appSetGenerator)
-
- if len(ret) == 0 {
- panic("no return value specified for GetTemplate")
- }
-
- var r0 *v1alpha1.ApplicationSetTemplate
- if returnFunc, ok := ret.Get(0).(func(*v1alpha1.ApplicationSetGenerator) *v1alpha1.ApplicationSetTemplate); ok {
- r0 = returnFunc(appSetGenerator)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*v1alpha1.ApplicationSetTemplate)
- }
- }
- return r0
-}
-
-// Generator_GetTemplate_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetTemplate'
-type Generator_GetTemplate_Call struct {
- *mock.Call
-}
-
-// GetTemplate is a helper method to define mock.On call
-// - appSetGenerator
-func (_e *Generator_Expecter) GetTemplate(appSetGenerator interface{}) *Generator_GetTemplate_Call {
- return &Generator_GetTemplate_Call{Call: _e.mock.On("GetTemplate", appSetGenerator)}
-}
-
-func (_c *Generator_GetTemplate_Call) Run(run func(appSetGenerator *v1alpha1.ApplicationSetGenerator)) *Generator_GetTemplate_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(*v1alpha1.ApplicationSetGenerator))
- })
- return _c
-}
-
-func (_c *Generator_GetTemplate_Call) Return(applicationSetTemplate *v1alpha1.ApplicationSetTemplate) *Generator_GetTemplate_Call {
- _c.Call.Return(applicationSetTemplate)
- return _c
-}
-
-func (_c *Generator_GetTemplate_Call) RunAndReturn(run func(appSetGenerator *v1alpha1.ApplicationSetGenerator) *v1alpha1.ApplicationSetTemplate) *Generator_GetTemplate_Call {
- _c.Call.Return(run)
- return _c
-}
diff --git a/applicationset/generators/plugin.go b/applicationset/generators/plugin.go
index 5db22571c5..6b6ba1ec40 100644
--- a/applicationset/generators/plugin.go
+++ b/applicationset/generators/plugin.go
@@ -2,7 +2,6 @@ package generators
import (
"context"
- "errors"
"fmt"
"strconv"
"strings"
@@ -13,14 +12,14 @@ import (
"k8s.io/client-go/kubernetes"
"sigs.k8s.io/controller-runtime/pkg/client"
- argoprojiov1alpha1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- "github.com/argoproj/argo-cd/v3/util/settings"
+ argoprojiov1alpha1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/util/settings"
- "github.com/argoproj/argo-cd/v3/applicationset/services/plugin"
+ "github.com/argoproj/argo-cd/v2/applicationset/services/plugin"
)
const (
- DefaultPluginRequeueAfter = 30 * time.Minute
+ DefaultPluginRequeueAfterSeconds = 30 * time.Minute
)
var _ Generator = (*PluginGenerator)(nil)
@@ -32,7 +31,7 @@ type PluginGenerator struct {
namespace string
}
-func NewPluginGenerator(ctx context.Context, client client.Client, clientset kubernetes.Interface, namespace string) Generator {
+func NewPluginGenerator(client client.Client, ctx context.Context, clientset kubernetes.Interface, namespace string) Generator {
g := &PluginGenerator{
client: client,
ctx: ctx,
@@ -49,20 +48,20 @@ func (g *PluginGenerator) GetRequeueAfter(appSetGenerator *argoprojiov1alpha1.Ap
return time.Duration(*appSetGenerator.Plugin.RequeueAfterSeconds) * time.Second
}
- return DefaultPluginRequeueAfter
+ return DefaultPluginRequeueAfterSeconds
}
func (g *PluginGenerator) GetTemplate(appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator) *argoprojiov1alpha1.ApplicationSetTemplate {
return &appSetGenerator.Plugin.Template
}
-func (g *PluginGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator, applicationSetInfo *argoprojiov1alpha1.ApplicationSet, _ client.Client) ([]map[string]any, error) {
+func (g *PluginGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator, applicationSetInfo *argoprojiov1alpha1.ApplicationSet, _ client.Client) ([]map[string]interface{}, error) {
if appSetGenerator == nil {
- return nil, ErrEmptyAppSetGenerator
+ return nil, EmptyAppSetGeneratorError
}
if appSetGenerator.Plugin == nil {
- return nil, ErrEmptyAppSetGenerator
+ return nil, EmptyAppSetGeneratorError
}
ctx := context.Background()
@@ -106,18 +105,18 @@ func (g *PluginGenerator) getPluginFromGenerator(ctx context.Context, appSetName
}
}
- pluginClient, err := plugin.NewPluginService(appSetName, cm["baseUrl"], token, requestTimeout)
+ pluginClient, err := plugin.NewPluginService(ctx, appSetName, cm["baseUrl"], token, requestTimeout)
if err != nil {
return nil, fmt.Errorf("error initializing plugin client: %w", err)
}
return pluginClient, nil
}
-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{}
+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{}{}
for _, objectFound := range objectsFound {
- params := map[string]any{}
+ params := map[string]interface{}{}
if useGoTemplate {
for k, v := range objectFound {
@@ -133,7 +132,7 @@ func (g *PluginGenerator) generateParams(appSetGenerator *argoprojiov1alpha1.App
}
}
- params["generator"] = map[string]any{
+ params["generator"] = map[string]interface{}{
"input": map[string]argoprojiov1alpha1.PluginParameters{
"parameters": pluginParams,
},
@@ -193,14 +192,14 @@ func (g *PluginGenerator) getConfigMap(ctx context.Context, configMapRef string)
return nil, err
}
- baseURL, ok := cm.Data["baseUrl"]
- if !ok || baseURL == "" {
- return nil, errors.New("baseUrl not found in ConfigMap")
+ baseUrl, ok := cm.Data["baseUrl"]
+ if !ok || baseUrl == "" {
+ return nil, fmt.Errorf("baseUrl not found in ConfigMap")
}
token, ok := cm.Data["token"]
if !ok || token == "" {
- return nil, errors.New("token not found in ConfigMap")
+ return nil, fmt.Errorf("token not found in ConfigMap")
}
return cm.Data, nil
diff --git a/applicationset/generators/plugin_test.go b/applicationset/generators/plugin_test.go
index 4940b64d44..0ade708ee5 100644
--- a/applicationset/generators/plugin_test.go
+++ b/applicationset/generators/plugin_test.go
@@ -1,8 +1,8 @@
package generators
import (
+ "context"
"encoding/json"
- "errors"
"fmt"
"net/http"
"net/http/httptest"
@@ -11,7 +11,7 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
- corev1 "k8s.io/api/core/v1"
+ v1 "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"
@@ -19,25 +19,25 @@ import (
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/fake"
- "github.com/argoproj/argo-cd/v3/applicationset/services/plugin"
- argoprojiov1alpha1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/applicationset/services/plugin"
+ argoprojiov1alpha1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
)
func TestPluginGenerateParams(t *testing.T) {
testCases := []struct {
name string
- configmap *corev1.ConfigMap
- secret *corev1.Secret
+ configmap *v1.ConfigMap
+ secret *v1.Secret
inputParameters map[string]apiextensionsv1.JSON
values map[string]string
gotemplate bool
- expected []map[string]any
+ expected []map[string]interface{}
content []byte
expectedError error
}{
{
name: "simple case",
- configmap: &corev1.ConfigMap{
+ configmap: &v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: "first-plugin-cm",
Namespace: "default",
@@ -47,7 +47,7 @@ func TestPluginGenerateParams(t *testing.T) {
"token": "$plugin.token",
},
},
- secret: &corev1.Secret{
+ secret: &v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "argocd-secret",
Namespace: "default",
@@ -73,13 +73,13 @@ func TestPluginGenerateParams(t *testing.T) {
"key3": 123
}]
}}`),
- expected: []map[string]any{
+ expected: []map[string]interface{}{
{
"key1": "val1",
"key2.key2_1": "val2_1",
"key2.key2_2.key2_2_1": "val2_2_1",
"key3": "123",
- "generator": map[string]any{
+ "generator": map[string]interface{}{
"input": argoprojiov1alpha1.PluginInput{
Parameters: argoprojiov1alpha1.PluginParameters{
"pkey1": {Raw: []byte(`"val1"`)},
@@ -93,7 +93,7 @@ func TestPluginGenerateParams(t *testing.T) {
},
{
name: "simple case with values",
- configmap: &corev1.ConfigMap{
+ configmap: &v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: "first-plugin-cm",
Namespace: "default",
@@ -103,7 +103,7 @@ func TestPluginGenerateParams(t *testing.T) {
"token": "$plugin.token",
},
},
- secret: &corev1.Secret{
+ secret: &v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "argocd-secret",
Namespace: "default",
@@ -133,7 +133,7 @@ func TestPluginGenerateParams(t *testing.T) {
"key3": 123
}]
}}`),
- expected: []map[string]any{
+ expected: []map[string]interface{}{
{
"key1": "val1",
"key2.key2_1": "val2_1",
@@ -141,7 +141,7 @@ func TestPluginGenerateParams(t *testing.T) {
"key3": "123",
"values.valuekey1": "valuevalue1",
"values.valuekey2": "templated-val1",
- "generator": map[string]any{
+ "generator": map[string]interface{}{
"input": argoprojiov1alpha1.PluginInput{
Parameters: argoprojiov1alpha1.PluginParameters{
"pkey1": {Raw: []byte(`"val1"`)},
@@ -155,7 +155,7 @@ func TestPluginGenerateParams(t *testing.T) {
},
{
name: "simple case with gotemplate",
- configmap: &corev1.ConfigMap{
+ configmap: &v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: "first-plugin-cm",
Namespace: "default",
@@ -165,7 +165,7 @@ func TestPluginGenerateParams(t *testing.T) {
"token": "$plugin.token",
},
},
- secret: &corev1.Secret{
+ secret: &v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "argocd-secret",
Namespace: "default",
@@ -191,17 +191,17 @@ func TestPluginGenerateParams(t *testing.T) {
"key3": 123
}]
}}`),
- expected: []map[string]any{
+ expected: []map[string]interface{}{
{
"key1": "val1",
- "key2": map[string]any{
+ "key2": map[string]interface{}{
"key2_1": "val2_1",
- "key2_2": map[string]any{
+ "key2_2": map[string]interface{}{
"key2_2_1": "val2_2_1",
},
},
"key3": float64(123),
- "generator": map[string]any{
+ "generator": map[string]interface{}{
"input": argoprojiov1alpha1.PluginInput{
Parameters: argoprojiov1alpha1.PluginParameters{
"pkey1": {Raw: []byte(`"val1"`)},
@@ -215,7 +215,7 @@ func TestPluginGenerateParams(t *testing.T) {
},
{
name: "simple case with appended params",
- configmap: &corev1.ConfigMap{
+ configmap: &v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: "first-plugin-cm",
Namespace: "default",
@@ -225,7 +225,7 @@ func TestPluginGenerateParams(t *testing.T) {
"token": "$plugin.token",
},
},
- secret: &corev1.Secret{
+ secret: &v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "argocd-secret",
Namespace: "default",
@@ -250,14 +250,14 @@ func TestPluginGenerateParams(t *testing.T) {
"key3": 123,
"pkey2": "valplugin"
}]}}`),
- expected: []map[string]any{
+ expected: []map[string]interface{}{
{
"key1": "val1",
"key2.key2_1": "val2_1",
"key2.key2_2.key2_2_1": "val2_2_1",
"key3": "123",
"pkey2": "valplugin",
- "generator": map[string]any{
+ "generator": map[string]interface{}{
"input": argoprojiov1alpha1.PluginInput{
Parameters: argoprojiov1alpha1.PluginParameters{
"pkey1": {Raw: []byte(`"val1"`)},
@@ -271,7 +271,7 @@ func TestPluginGenerateParams(t *testing.T) {
},
{
name: "no params",
- configmap: &corev1.ConfigMap{
+ configmap: &v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: "first-plugin-cm",
Namespace: "default",
@@ -281,7 +281,7 @@ func TestPluginGenerateParams(t *testing.T) {
"token": "$plugin.token",
},
},
- secret: &corev1.Secret{
+ secret: &v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "argocd-secret",
Namespace: "default",
@@ -304,14 +304,14 @@ func TestPluginGenerateParams(t *testing.T) {
"key3": 123
}]
}}`),
- expected: []map[string]any{
+ expected: []map[string]interface{}{
{
"key1": "val1",
"key2.key2_1": "val2_1",
"key2.key2_2.key2_2_1": "val2_2_1",
"key3": "123",
- "generator": map[string]any{
- "input": map[string]map[string]any{
+ "generator": map[string]interface{}{
+ "input": map[string]map[string]interface{}{
"parameters": {},
},
},
@@ -321,7 +321,7 @@ func TestPluginGenerateParams(t *testing.T) {
},
{
name: "empty return",
- configmap: &corev1.ConfigMap{
+ configmap: &v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: "first-plugin-cm",
Namespace: "default",
@@ -331,7 +331,7 @@ func TestPluginGenerateParams(t *testing.T) {
"token": "$plugin.token",
},
},
- secret: &corev1.Secret{
+ secret: &v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "argocd-secret",
Namespace: "default",
@@ -343,12 +343,12 @@ func TestPluginGenerateParams(t *testing.T) {
inputParameters: map[string]apiextensionsv1.JSON{},
gotemplate: false,
content: []byte(`{"input": {"parameters": []}}`),
- expected: []map[string]any{},
+ expected: []map[string]interface{}{},
expectedError: nil,
},
{
name: "wrong return",
- configmap: &corev1.ConfigMap{
+ configmap: &v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: "first-plugin-cm",
Namespace: "default",
@@ -358,7 +358,7 @@ func TestPluginGenerateParams(t *testing.T) {
"token": "$plugin.token",
},
},
- secret: &corev1.Secret{
+ secret: &v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "argocd-secret",
Namespace: "default",
@@ -370,12 +370,12 @@ func TestPluginGenerateParams(t *testing.T) {
inputParameters: map[string]apiextensionsv1.JSON{},
gotemplate: false,
content: []byte(`wrong body ...`),
- expected: []map[string]any{},
- expectedError: errors.New("error listing params: error get api 'set': invalid character 'w' looking for beginning of value: wrong body ..."),
+ expected: []map[string]interface{}{},
+ expectedError: fmt.Errorf("error listing params: error get api 'set': invalid character 'w' looking for beginning of value: wrong body ..."),
},
{
name: "external secret",
- configmap: &corev1.ConfigMap{
+ configmap: &v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: "first-plugin-cm",
Namespace: "default",
@@ -385,7 +385,7 @@ func TestPluginGenerateParams(t *testing.T) {
"token": "$plugin-secret:plugin.token",
},
},
- secret: &corev1.Secret{
+ secret: &v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "plugin-secret",
Namespace: "default",
@@ -410,14 +410,14 @@ func TestPluginGenerateParams(t *testing.T) {
"key3": 123,
"pkey2": "valplugin"
}]}}`),
- expected: []map[string]any{
+ expected: []map[string]interface{}{
{
"key1": "val1",
"key2.key2_1": "val2_1",
"key2.key2_2.key2_2_1": "val2_2_1",
"key3": "123",
"pkey2": "valplugin",
- "generator": map[string]any{
+ "generator": map[string]interface{}{
"input": argoprojiov1alpha1.PluginInput{
Parameters: argoprojiov1alpha1.PluginParameters{
"pkey1": {Raw: []byte(`"val1"`)},
@@ -431,7 +431,7 @@ func TestPluginGenerateParams(t *testing.T) {
},
{
name: "no secret",
- configmap: &corev1.ConfigMap{
+ configmap: &v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: "first-plugin-cm",
Namespace: "default",
@@ -441,7 +441,7 @@ func TestPluginGenerateParams(t *testing.T) {
"token": "$plugin.token",
},
},
- secret: &corev1.Secret{},
+ secret: &v1.Secret{},
inputParameters: map[string]apiextensionsv1.JSON{
"pkey1": {Raw: []byte(`"val1"`)},
"pkey2": {Raw: []byte(`"val2"`)},
@@ -459,13 +459,13 @@ func TestPluginGenerateParams(t *testing.T) {
"key3": 123
}]
}}`),
- expected: []map[string]any{
+ expected: []map[string]interface{}{
{
"key1": "val1",
"key2.key2_1": "val2_1",
"key2.key2_2.key2_2_1": "val2_2_1",
"key3": "123",
- "generator": map[string]any{
+ "generator": map[string]interface{}{
"input": argoprojiov1alpha1.PluginInput{
Parameters: argoprojiov1alpha1.PluginParameters{
"pkey1": {Raw: []byte(`"val1"`)},
@@ -475,12 +475,12 @@ func TestPluginGenerateParams(t *testing.T) {
},
},
},
- expectedError: errors.New("error getting plugin from generator: error fetching Secret token: error fetching secret default/argocd-secret: secrets \"argocd-secret\" not found"),
+ expectedError: fmt.Errorf("error getting plugin from generator: error fetching Secret token: error fetching secret default/argocd-secret: secrets \"argocd-secret\" not found"),
},
{
name: "no configmap",
- configmap: &corev1.ConfigMap{},
- secret: &corev1.Secret{
+ configmap: &v1.ConfigMap{},
+ secret: &v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "argocd-secret",
Namespace: "default",
@@ -506,13 +506,13 @@ func TestPluginGenerateParams(t *testing.T) {
"key3": 123
}]
}}`),
- expected: []map[string]any{
+ expected: []map[string]interface{}{
{
"key1": "val1",
"key2.key2_1": "val2_1",
"key2.key2_2.key2_2_1": "val2_2_1",
"key3": "123",
- "generator": map[string]any{
+ "generator": map[string]interface{}{
"input": argoprojiov1alpha1.PluginInput{
Parameters: argoprojiov1alpha1.PluginParameters{
"pkey1": {Raw: []byte(`"val1"`)},
@@ -522,11 +522,11 @@ func TestPluginGenerateParams(t *testing.T) {
},
},
},
- expectedError: errors.New("error getting plugin from generator: error fetching ConfigMap: configmaps \"\" not found"),
+ expectedError: fmt.Errorf("error getting plugin from generator: error fetching ConfigMap: configmaps \"\" not found"),
},
{
name: "no baseUrl",
- configmap: &corev1.ConfigMap{
+ configmap: &v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: "first-plugin-cm",
Namespace: "default",
@@ -535,7 +535,7 @@ func TestPluginGenerateParams(t *testing.T) {
"token": "$plugin.token",
},
},
- secret: &corev1.Secret{
+ secret: &v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "argocd-secret",
Namespace: "default",
@@ -561,13 +561,13 @@ func TestPluginGenerateParams(t *testing.T) {
"key3": 123
}]
}}`),
- expected: []map[string]any{
+ expected: []map[string]interface{}{
{
"key1": "val1",
"key2.key2_1": "val2_1",
"key2.key2_2.key2_2_1": "val2_2_1",
"key3": "123",
- "generator": map[string]any{
+ "generator": map[string]interface{}{
"input": argoprojiov1alpha1.PluginInput{
Parameters: argoprojiov1alpha1.PluginParameters{
"pkey1": {Raw: []byte(`"val1"`)},
@@ -577,11 +577,11 @@ func TestPluginGenerateParams(t *testing.T) {
},
},
},
- expectedError: errors.New("error getting plugin from generator: error fetching ConfigMap: baseUrl not found in ConfigMap"),
+ expectedError: fmt.Errorf("error getting plugin from generator: error fetching ConfigMap: baseUrl not found in ConfigMap"),
},
{
name: "no token",
- configmap: &corev1.ConfigMap{
+ configmap: &v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: "first-plugin-cm",
Namespace: "default",
@@ -590,7 +590,7 @@ func TestPluginGenerateParams(t *testing.T) {
"baseUrl": "http://127.0.0.1",
},
},
- secret: &corev1.Secret{},
+ secret: &v1.Secret{},
inputParameters: map[string]apiextensionsv1.JSON{
"pkey1": {Raw: []byte(`"val1"`)},
"pkey2": {Raw: []byte(`"val2"`)},
@@ -608,13 +608,13 @@ func TestPluginGenerateParams(t *testing.T) {
"key3": 123
}]
}}`),
- expected: []map[string]any{
+ expected: []map[string]interface{}{
{
"key1": "val1",
"key2.key2_1": "val2_1",
"key2.key2_2.key2_2_1": "val2_2_1",
"key3": "123",
- "generator": map[string]any{
+ "generator": map[string]interface{}{
"input": argoprojiov1alpha1.PluginInput{
Parameters: argoprojiov1alpha1.PluginParameters{
"pkey1": {Raw: []byte(`"val1"`)},
@@ -624,11 +624,11 @@ func TestPluginGenerateParams(t *testing.T) {
},
},
},
- expectedError: errors.New("error getting plugin from generator: error fetching ConfigMap: token not found in ConfigMap"),
+ expectedError: fmt.Errorf("error getting plugin from generator: error fetching ConfigMap: token not found in ConfigMap"),
},
}
- ctx := t.Context()
+ ctx := context.Background()
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
@@ -670,7 +670,7 @@ func TestPluginGenerateParams(t *testing.T) {
fakeClientWithCache := fake.NewClientBuilder().WithObjects([]client.Object{testCase.configmap, testCase.secret}...).Build()
- pluginGenerator := NewPluginGenerator(ctx, fakeClientWithCache, fakeClient, "default")
+ pluginGenerator := NewPluginGenerator(fakeClientWithCache, ctx, fakeClient, "default")
applicationSetInfo := argoprojiov1alpha1.ApplicationSet{
ObjectMeta: metav1.ObjectMeta{
@@ -690,11 +690,11 @@ func TestPluginGenerateParams(t *testing.T) {
require.EqualError(t, err, testCase.expectedError.Error())
} else {
require.NoError(t, err)
- expectedJSON, err := json.Marshal(testCase.expected)
+ expectedJson, err := json.Marshal(testCase.expected)
require.NoError(t, err)
- gotJSON, err := json.Marshal(got)
+ gotJson, err := json.Marshal(got)
require.NoError(t, err)
- assert.JSONEq(t, string(expectedJSON), string(gotJSON))
+ assert.JSONEq(t, string(expectedJson), string(gotJson))
}
})
}
diff --git a/applicationset/generators/pull_request.go b/applicationset/generators/pull_request.go
index 0059f249b0..f0c2bfaacf 100644
--- a/applicationset/generators/pull_request.go
+++ b/applicationset/generators/pull_request.go
@@ -2,7 +2,6 @@ package generators
import (
"context"
- "errors"
"fmt"
"strconv"
"time"
@@ -11,15 +10,15 @@ import (
"github.com/gosimple/slug"
- pullrequest "github.com/argoproj/argo-cd/v3/applicationset/services/pull_request"
- "github.com/argoproj/argo-cd/v3/applicationset/utils"
- argoprojiov1alpha1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ pullrequest "github.com/argoproj/argo-cd/v2/applicationset/services/pull_request"
+ "github.com/argoproj/argo-cd/v2/applicationset/utils"
+ argoprojiov1alpha1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
)
var _ Generator = (*PullRequestGenerator)(nil)
const (
- DefaultPullRequestRequeueAfter = 30 * time.Minute
+ DefaultPullRequestRequeueAfterSeconds = 30 * time.Minute
)
type PullRequestGenerator struct {
@@ -44,20 +43,20 @@ func (g *PullRequestGenerator) GetRequeueAfter(appSetGenerator *argoprojiov1alph
return time.Duration(*appSetGenerator.PullRequest.RequeueAfterSeconds) * time.Second
}
- return DefaultPullRequestRequeueAfter
+ return DefaultPullRequestRequeueAfterSeconds
}
func (g *PullRequestGenerator) GetTemplate(appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator) *argoprojiov1alpha1.ApplicationSetTemplate {
return &appSetGenerator.PullRequest.Template
}
-func (g *PullRequestGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator, applicationSetInfo *argoprojiov1alpha1.ApplicationSet, _ client.Client) ([]map[string]any, error) {
+func (g *PullRequestGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator, applicationSetInfo *argoprojiov1alpha1.ApplicationSet, _ client.Client) ([]map[string]interface{}, error) {
if appSetGenerator == nil {
- return nil, ErrEmptyAppSetGenerator
+ return nil, EmptyAppSetGeneratorError
}
if appSetGenerator.PullRequest == nil {
- return nil, ErrEmptyAppSetGenerator
+ return nil, EmptyAppSetGeneratorError
}
ctx := context.Background()
@@ -70,7 +69,7 @@ func (g *PullRequestGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha
if err != nil {
return nil, fmt.Errorf("error listing repos: %w", err)
}
- params := make([]map[string]any, 0, len(pulls))
+ params := make([]map[string]interface{}, 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 +95,7 @@ func (g *PullRequestGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha
shortSHALength7 = len(pull.HeadSHA)
}
- paramMap := map[string]any{
+ paramMap := map[string]interface{}{
"number": strconv.Itoa(pull.Number),
"title": pull.Title,
"branch": pull.Branch,
@@ -109,11 +108,6 @@ func (g *PullRequestGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha
"author": pull.Author,
}
- err := appendTemplatedValues(appSetGenerator.PullRequest.Values, paramMap, applicationSetInfo.Spec.GoTemplate, applicationSetInfo.Spec.GoTemplateOptions)
- if err != nil {
- return nil, fmt.Errorf("failed to append templated values: %w", err)
- }
-
// PR lables will only be supported for Go Template appsets, since fasttemplate will be deprecated.
if applicationSetInfo != nil && applicationSetInfo.Spec.GoTemplate {
paramMap["labels"] = pull.Labels
@@ -149,7 +143,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(token, providerConfig.API, providerConfig.Project, providerConfig.Labels, providerConfig.PullRequestState, g.scmRootCAPath, providerConfig.Insecure, caCerts)
+ return pullrequest.NewGitLabService(ctx, token, providerConfig.API, providerConfig.Project, providerConfig.Labels, providerConfig.PullRequestState, g.scmRootCAPath, providerConfig.Insecure, caCerts)
}
if generatorConfig.Gitea != nil {
providerConfig := generatorConfig.Gitea
@@ -157,8 +151,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(token, providerConfig.API, providerConfig.Owner, providerConfig.Repo, providerConfig.Labels, providerConfig.Insecure)
+ return pullrequest.NewGiteaService(ctx, token, providerConfig.API, providerConfig.Owner, providerConfig.Repo, providerConfig.Insecure)
}
if generatorConfig.BitbucketServer != nil {
providerConfig := generatorConfig.BitbucketServer
@@ -182,8 +175,9 @@ 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
@@ -199,8 +193,9 @@ 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
@@ -208,9 +203,9 @@ func (g *PullRequestGenerator) selectServiceProvider(ctx context.Context, genera
if err != nil {
return nil, fmt.Errorf("error fetching Secret token: %w", err)
}
- return pullrequest.NewAzureDevOpsService(token, providerConfig.API, providerConfig.Organization, providerConfig.Project, providerConfig.Repo, providerConfig.Labels)
+ return pullrequest.NewAzureDevOpsService(ctx, token, providerConfig.API, providerConfig.Organization, providerConfig.Project, providerConfig.Repo, providerConfig.Labels)
}
- return nil, errors.New("no Pull Request provider implementation configured")
+ return nil, fmt.Errorf("no Pull Request provider implementation configured")
}
func (g *PullRequestGenerator) github(ctx context.Context, cfg *argoprojiov1alpha1.PullRequestGeneratorGithub, applicationSetInfo *argoprojiov1alpha1.ApplicationSet) (pullrequest.PullRequestService, error) {
@@ -228,5 +223,5 @@ func (g *PullRequestGenerator) github(ctx context.Context, cfg *argoprojiov1alph
if err != nil {
return nil, fmt.Errorf("error fetching Secret token: %w", err)
}
- return pullrequest.NewGithubService(token, cfg.API, cfg.Owner, cfg.Repo, cfg.Labels)
+ return pullrequest.NewGithubService(ctx, token, cfg.API, cfg.Owner, cfg.Repo, cfg.Labels)
}
diff --git a/applicationset/generators/pull_request_test.go b/applicationset/generators/pull_request_test.go
index 8cfbf7920d..d4eae1602b 100644
--- a/applicationset/generators/pull_request_test.go
+++ b/applicationset/generators/pull_request_test.go
@@ -2,23 +2,22 @@ package generators
import (
"context"
- "errors"
+ "fmt"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
- pullrequest "github.com/argoproj/argo-cd/v3/applicationset/services/pull_request"
- argoprojiov1alpha1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ pullrequest "github.com/argoproj/argo-cd/v2/applicationset/services/pull_request"
+ argoprojiov1alpha1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
)
func TestPullRequestGithubGenerateParams(t *testing.T) {
- ctx := t.Context()
+ ctx := context.Background()
cases := []struct {
selectFunc func(context.Context, *argoprojiov1alpha1.PullRequestGenerator, *argoprojiov1alpha1.ApplicationSet) (pullrequest.PullRequestService, error)
- values map[string]string
- expected []map[string]any
+ expected []map[string]interface{}
expectedErr error
applicationSet argoprojiov1alpha1.ApplicationSet
}{
@@ -39,7 +38,7 @@ func TestPullRequestGithubGenerateParams(t *testing.T) {
nil,
)
},
- expected: []map[string]any{
+ expected: []map[string]interface{}{
{
"number": "1",
"title": "title1",
@@ -72,7 +71,7 @@ func TestPullRequestGithubGenerateParams(t *testing.T) {
nil,
)
},
- expected: []map[string]any{
+ expected: []map[string]interface{}{
{
"number": "2",
"title": "title2",
@@ -105,7 +104,7 @@ func TestPullRequestGithubGenerateParams(t *testing.T) {
nil,
)
},
- expected: []map[string]any{
+ expected: []map[string]interface{}{
{
"number": "1",
"title": "title1",
@@ -125,51 +124,12 @@ func TestPullRequestGithubGenerateParams(t *testing.T) {
selectFunc: func(context.Context, *argoprojiov1alpha1.PullRequestGenerator, *argoprojiov1alpha1.ApplicationSet) (pullrequest.PullRequestService, error) {
return pullrequest.NewFakeService(
ctx,
- []*pullrequest.PullRequest{
- {
- Number: 1,
- Title: "title1",
- Branch: "my_branch",
- TargetBranch: "master",
- HeadSHA: "abcd",
- Author: "testName",
- },
- },
nil,
- )
- },
- values: map[string]string{
- "foo": "bar",
- "pr_branch": "{{ branch }}",
- },
- expected: []map[string]any{
- {
- "number": "1",
- "title": "title1",
- "branch": "my_branch",
- "branch_slug": "my-branch",
- "target_branch": "master",
- "target_branch_slug": "master",
- "head_sha": "abcd",
- "head_short_sha": "abcd",
- "head_short_sha_7": "abcd",
- "author": "testName",
- "values.foo": "bar",
- "values.pr_branch": "my_branch",
- },
- },
- expectedErr: nil,
- },
- {
- selectFunc: func(context.Context, *argoprojiov1alpha1.PullRequestGenerator, *argoprojiov1alpha1.ApplicationSet) (pullrequest.PullRequestService, error) {
- return pullrequest.NewFakeService(
- ctx,
- nil,
- errors.New("fake error"),
+ fmt.Errorf("fake error"),
)
},
expected: nil,
- expectedErr: errors.New("error listing repos: fake error"),
+ expectedErr: fmt.Errorf("error listing repos: fake error"),
},
{
selectFunc: func(context.Context, *argoprojiov1alpha1.PullRequestGenerator, *argoprojiov1alpha1.ApplicationSet) (pullrequest.PullRequestService, error) {
@@ -189,7 +149,7 @@ func TestPullRequestGithubGenerateParams(t *testing.T) {
nil,
)
},
- expected: []map[string]any{
+ expected: []map[string]interface{}{
{
"number": "1",
"title": "title1",
@@ -230,7 +190,7 @@ func TestPullRequestGithubGenerateParams(t *testing.T) {
nil,
)
},
- expected: []map[string]any{
+ expected: []map[string]interface{}{
{
"number": "1",
"title": "title1",
@@ -259,14 +219,12 @@ func TestPullRequestGithubGenerateParams(t *testing.T) {
selectServiceProviderFunc: c.selectFunc,
}
generatorConfig := argoprojiov1alpha1.ApplicationSetGenerator{
- PullRequest: &argoprojiov1alpha1.PullRequestGenerator{
- Values: c.values,
- },
+ PullRequest: &argoprojiov1alpha1.PullRequestGenerator{},
}
got, gotErr := gen.GenerateParams(&generatorConfig, &c.applicationSet, nil)
if c.expectedErr != nil {
- require.EqualError(t, gotErr, c.expectedErr.Error())
+ assert.Equal(t, c.expectedErr.Error(), gotErr.Error())
} else {
require.NoError(t, gotErr)
}
diff --git a/applicationset/generators/scm_provider.go b/applicationset/generators/scm_provider.go
index 560a37050d..417b682e50 100644
--- a/applicationset/generators/scm_provider.go
+++ b/applicationset/generators/scm_provider.go
@@ -11,17 +11,17 @@ import (
log "github.com/sirupsen/logrus"
- "github.com/argoproj/argo-cd/v3/applicationset/services/github_app_auth"
- "github.com/argoproj/argo-cd/v3/applicationset/services/scm_provider"
- "github.com/argoproj/argo-cd/v3/applicationset/utils"
- "github.com/argoproj/argo-cd/v3/common"
- argoprojiov1alpha1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/applicationset/services/github_app_auth"
+ "github.com/argoproj/argo-cd/v2/applicationset/services/scm_provider"
+ "github.com/argoproj/argo-cd/v2/applicationset/utils"
+ "github.com/argoproj/argo-cd/v2/common"
+ argoprojiov1alpha1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
)
var _ Generator = (*SCMProviderGenerator)(nil)
const (
- DefaultSCMProviderRequeueAfter = 30 * time.Minute
+ DefaultSCMProviderRequeueAfterSeconds = 30 * time.Minute
)
type SCMProviderGenerator struct {
@@ -69,7 +69,7 @@ func (g *SCMProviderGenerator) GetRequeueAfter(appSetGenerator *argoprojiov1alph
return time.Duration(*appSetGenerator.SCMProvider.RequeueAfterSeconds) * time.Second
}
- return DefaultSCMProviderRequeueAfter
+ return DefaultSCMProviderRequeueAfterSeconds
}
func (g *SCMProviderGenerator) GetTemplate(appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator) *argoprojiov1alpha1.ApplicationSetTemplate {
@@ -116,13 +116,13 @@ func ScmProviderAllowed(applicationSetInfo *argoprojiov1alpha1.ApplicationSet, g
return NewErrDisallowedSCMProvider(url, allowedScmProviders)
}
-func (g *SCMProviderGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator, applicationSetInfo *argoprojiov1alpha1.ApplicationSet, _ client.Client) ([]map[string]any, error) {
+func (g *SCMProviderGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha1.ApplicationSetGenerator, applicationSetInfo *argoprojiov1alpha1.ApplicationSet, _ client.Client) ([]map[string]interface{}, error) {
if appSetGenerator == nil {
- return nil, ErrEmptyAppSetGenerator
+ return nil, EmptyAppSetGeneratorError
}
if appSetGenerator.SCMProvider == nil {
- return nil, ErrEmptyAppSetGenerator
+ return nil, EmptyAppSetGeneratorError
}
if !g.enableSCMProviders {
@@ -138,16 +138,15 @@ func (g *SCMProviderGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha
ctx := context.Background()
var provider scm_provider.SCMProviderService
- switch {
- case g.overrideProvider != nil:
+ if g.overrideProvider != nil {
provider = g.overrideProvider
- case providerConfig.Github != nil:
+ } else if providerConfig.Github != nil {
var err error
provider, err = g.githubProvider(ctx, providerConfig.Github, applicationSetInfo)
if err != nil {
return nil, fmt.Errorf("scm provider: %w", err)
}
- case providerConfig.Gitlab != nil:
+ } else if providerConfig.Gitlab != nil {
providerConfig := providerConfig.Gitlab
var caCerts []byte
var scmError error
@@ -161,20 +160,20 @@ func (g *SCMProviderGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha
if err != nil {
return nil, fmt.Errorf("error fetching Gitlab token: %w", err)
}
- provider, err = scm_provider.NewGitlabProvider(providerConfig.Group, token, providerConfig.API, providerConfig.AllBranches, providerConfig.IncludeSubgroups, providerConfig.WillIncludeSharedProjects(), providerConfig.Insecure, g.scmRootCAPath, providerConfig.Topic, caCerts)
+ provider, err = scm_provider.NewGitlabProvider(ctx, 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)
}
- case providerConfig.Gitea != nil:
+ } else if providerConfig.Gitea != nil {
token, err := utils.GetSecretRef(ctx, g.client, providerConfig.Gitea.TokenRef, applicationSetInfo.Namespace, g.tokenRefStrictMode)
if err != nil {
return nil, fmt.Errorf("error fetching Gitea token: %w", err)
}
- provider, err = scm_provider.NewGiteaProvider(providerConfig.Gitea.Owner, token, providerConfig.Gitea.API, providerConfig.Gitea.AllBranches, providerConfig.Gitea.Insecure)
+ provider, err = scm_provider.NewGiteaProvider(ctx, 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)
}
- case providerConfig.BitbucketServer != nil:
+ } else if providerConfig.BitbucketServer != nil {
providerConfig := providerConfig.BitbucketServer
var caCerts []byte
var scmError error
@@ -184,51 +183,50 @@ func (g *SCMProviderGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha
return nil, fmt.Errorf("error fetching CA certificates from ConfigMap: %w", scmError)
}
}
- switch {
- case providerConfig.BearerToken != nil:
+ if providerConfig.BearerToken != nil {
appToken, err := utils.GetSecretRef(ctx, g.client, providerConfig.BearerToken.TokenRef, applicationSetInfo.Namespace, g.tokenRefStrictMode)
if err != nil {
return nil, fmt.Errorf("error fetching Secret Bearer token: %w", err)
}
provider, scmError = scm_provider.NewBitbucketServerProviderBearerToken(ctx, appToken, providerConfig.API, providerConfig.Project, providerConfig.AllBranches, g.scmRootCAPath, providerConfig.Insecure, caCerts)
- case providerConfig.BasicAuth != nil:
+ } else if providerConfig.BasicAuth != nil {
password, err := utils.GetSecretRef(ctx, g.client, providerConfig.BasicAuth.PasswordRef, applicationSetInfo.Namespace, g.tokenRefStrictMode)
if err != nil {
return nil, fmt.Errorf("error fetching Secret token: %w", err)
}
provider, scmError = scm_provider.NewBitbucketServerProviderBasicAuth(ctx, providerConfig.BasicAuth.Username, password, providerConfig.API, providerConfig.Project, providerConfig.AllBranches, g.scmRootCAPath, providerConfig.Insecure, caCerts)
- default:
+ } else {
provider, scmError = scm_provider.NewBitbucketServerProviderNoAuth(ctx, providerConfig.API, providerConfig.Project, providerConfig.AllBranches, g.scmRootCAPath, providerConfig.Insecure, caCerts)
}
if scmError != nil {
return nil, fmt.Errorf("error initializing Bitbucket Server service: %w", scmError)
}
- case providerConfig.AzureDevOps != nil:
+ } else if providerConfig.AzureDevOps != nil {
token, err := utils.GetSecretRef(ctx, g.client, providerConfig.AzureDevOps.AccessTokenRef, applicationSetInfo.Namespace, g.tokenRefStrictMode)
if err != nil {
return nil, fmt.Errorf("error fetching Azure Devops access token: %w", err)
}
- provider, err = scm_provider.NewAzureDevOpsProvider(token, providerConfig.AzureDevOps.Organization, providerConfig.AzureDevOps.API, providerConfig.AzureDevOps.TeamProject, providerConfig.AzureDevOps.AllBranches)
+ provider, err = scm_provider.NewAzureDevOpsProvider(ctx, 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)
}
- case providerConfig.Bitbucket != nil:
+ } else if providerConfig.Bitbucket != nil {
appPassword, err := utils.GetSecretRef(ctx, g.client, providerConfig.Bitbucket.AppPasswordRef, applicationSetInfo.Namespace, g.tokenRefStrictMode)
if err != nil {
return nil, fmt.Errorf("error fetching Bitbucket cloud appPassword: %w", err)
}
- provider, err = scm_provider.NewBitBucketCloudProvider(providerConfig.Bitbucket.Owner, providerConfig.Bitbucket.User, appPassword, providerConfig.Bitbucket.AllBranches)
+ provider, err = scm_provider.NewBitBucketCloudProvider(ctx, providerConfig.Bitbucket.Owner, providerConfig.Bitbucket.User, appPassword, providerConfig.Bitbucket.AllBranches)
if err != nil {
return nil, fmt.Errorf("error initializing Bitbucket cloud service: %w", err)
}
- case providerConfig.AWSCodeCommit != nil:
+ } else if providerConfig.AWSCodeCommit != nil {
var awsErr error
provider, awsErr = scm_provider.NewAWSCodeCommitProvider(ctx, providerConfig.AWSCodeCommit.TagFilters, providerConfig.AWSCodeCommit.Role, providerConfig.AWSCodeCommit.Region, providerConfig.AWSCodeCommit.AllBranches)
if awsErr != nil {
return nil, fmt.Errorf("error initializing AWS codecommit service: %w", awsErr)
}
- default:
- return nil, errors.New("no SCM provider implementation configured")
+ } else {
+ return nil, fmt.Errorf("no SCM provider implementation configured")
}
// Find all the available repos.
@@ -236,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]any, 0, len(repos))
+ paramsArray := make([]map[string]interface{}, 0, len(repos))
var shortSHALength int
var shortSHALength7 int
for _, repo := range repos {
@@ -250,10 +248,9 @@ func (g *SCMProviderGenerator) GenerateParams(appSetGenerator *argoprojiov1alpha
shortSHALength7 = len(repo.SHA)
}
- params := map[string]any{
+ params := map[string]interface{}{
"organization": repo.Organization,
"repository": repo.Repository,
- "repository_id": repo.RepositoryId,
"url": repo.URL,
"branch": repo.Branch,
"sha": repo.SHA,
@@ -292,5 +289,5 @@ func (g *SCMProviderGenerator) githubProvider(ctx context.Context, github *argop
if err != nil {
return nil, fmt.Errorf("error fetching Github token: %w", err)
}
- return scm_provider.NewGithubProvider(github.Organization, token, github.API, github.AllBranches)
+ return scm_provider.NewGithubProvider(ctx, github.Organization, token, github.API, github.AllBranches)
}
diff --git a/applicationset/generators/scm_provider_test.go b/applicationset/generators/scm_provider_test.go
index 9d7618c869..a52f7e8159 100644
--- a/applicationset/generators/scm_provider_test.go
+++ b/applicationset/generators/scm_provider_test.go
@@ -7,8 +7,8 @@ import (
"github.com/stretchr/testify/require"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
- "github.com/argoproj/argo-cd/v3/applicationset/services/scm_provider"
- argoprojiov1alpha1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/applicationset/services/scm_provider"
+ argoprojiov1alpha1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
)
func TestSCMProviderGenerateParams(t *testing.T) {
@@ -16,7 +16,7 @@ func TestSCMProviderGenerateParams(t *testing.T) {
name string
repos []*scm_provider.Repository
values map[string]string
- expected []map[string]any
+ expected []map[string]interface{}
expectedError error
}{
{
@@ -25,7 +25,6 @@ func TestSCMProviderGenerateParams(t *testing.T) {
{
Organization: "myorg",
Repository: "repo1",
- RepositoryId: 190320251,
URL: "git@github.com:myorg/repo1.git",
Branch: "main",
SHA: "0bc57212c3cbbec69d20b34c507284bd300def5b",
@@ -34,17 +33,15 @@ func TestSCMProviderGenerateParams(t *testing.T) {
{
Organization: "myorg",
Repository: "repo2",
- RepositoryId: 190320252,
URL: "git@github.com:myorg/repo2.git",
Branch: "main",
SHA: "59d0",
},
},
- expected: []map[string]any{
+ expected: []map[string]interface{}{
{
"organization": "myorg",
"repository": "repo1",
- "repository_id": 190320251,
"url": "git@github.com:myorg/repo1.git",
"branch": "main",
"branchNormalized": "main",
@@ -56,7 +53,6 @@ func TestSCMProviderGenerateParams(t *testing.T) {
{
"organization": "myorg",
"repository": "repo2",
- "repository_id": 190320252,
"url": "git@github.com:myorg/repo2.git",
"branch": "main",
"branchNormalized": "main",
@@ -73,7 +69,6 @@ func TestSCMProviderGenerateParams(t *testing.T) {
{
Organization: "myorg",
Repository: "repo3",
- RepositoryId: 190320253,
URL: "git@github.com:myorg/repo3.git",
Branch: "main",
SHA: "0bc57212c3cbbec69d20b34c507284bd300def5b",
@@ -84,11 +79,10 @@ func TestSCMProviderGenerateParams(t *testing.T) {
"foo": "bar",
"should_i_force_push_to": "{{ branch }}?",
},
- expected: []map[string]any{
+ expected: []map[string]interface{}{
{
"organization": "myorg",
"repository": "repo3",
- "repository_id": 190320253,
"url": "git@github.com:myorg/repo3.git",
"branch": "main",
"branchNormalized": "main",
@@ -101,52 +95,6 @@ func TestSCMProviderGenerateParams(t *testing.T) {
},
},
},
- {
- name: "Repos with and without id",
- repos: []*scm_provider.Repository{
- {
- Organization: "myorg",
- Repository: "repo4",
- RepositoryId: "idaz09",
- URL: "git@github.com:myorg/repo4.git",
- Branch: "main",
- SHA: "0bc57212c3cbbec69d20b34c507284bd300def5b",
- },
- {
- Organization: "myorg",
- Repository: "repo5",
- URL: "git@github.com:myorg/repo5.git",
- Branch: "main",
- SHA: "0bc57212c3cbbec69d20b34c507284bd300def5b",
- },
- },
- expected: []map[string]any{
- {
- "organization": "myorg",
- "repository": "repo4",
- "repository_id": "idaz09",
- "url": "git@github.com:myorg/repo4.git",
- "branch": "main",
- "branchNormalized": "main",
- "sha": "0bc57212c3cbbec69d20b34c507284bd300def5b",
- "short_sha": "0bc57212",
- "short_sha_7": "0bc5721",
- "labels": "",
- },
- {
- "organization": "myorg",
- "repository": "repo5",
- "repository_id": nil,
- "url": "git@github.com:myorg/repo5.git",
- "branch": "main",
- "branchNormalized": "main",
- "sha": "0bc57212c3cbbec69d20b34c507284bd300def5b",
- "short_sha": "0bc57212",
- "short_sha_7": "0bc5721",
- "labels": "",
- },
- },
- },
}
for _, testCase := range cases {
diff --git a/applicationset/generators/scm_utils.go b/applicationset/generators/scm_utils.go
index 8fa6616a42..51ac99d9b7 100644
--- a/applicationset/generators/scm_utils.go
+++ b/applicationset/generators/scm_utils.go
@@ -1,5 +1,5 @@
package generators
-type SCMGeneratorWithCustomApiUrl interface { //nolint:revive //FIXME(var-naming)
+type SCMGeneratorWithCustomApiUrl interface {
CustomApiUrl() string
}
diff --git a/applicationset/generators/utils.go b/applicationset/generators/utils.go
index fe9e710179..84bdda6101 100644
--- a/applicationset/generators/utils.go
+++ b/applicationset/generators/utils.go
@@ -7,18 +7,18 @@ import (
"k8s.io/client-go/kubernetes"
"sigs.k8s.io/controller-runtime/pkg/client"
- "github.com/argoproj/argo-cd/v3/applicationset/services"
+ "github.com/argoproj/argo-cd/v2/applicationset/services"
)
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(ctx, c, k8sClient, namespace),
+ "Clusters": NewClusterGenerator(c, ctx, k8sClient, namespace),
"Git": NewGitGenerator(argoCDService, namespace),
"SCMProvider": NewSCMProviderGenerator(c, scmConfig),
"ClusterDecisionResource": NewDuckTypeGenerator(ctx, dynamicClient, k8sClient, namespace),
"PullRequest": NewPullRequestGenerator(c, scmConfig),
- "Plugin": NewPluginGenerator(ctx, c, k8sClient, namespace),
+ "Plugin": NewPluginGenerator(c, ctx, k8sClient, namespace),
}
nestedGenerators := map[string]Generator{
diff --git a/applicationset/generators/value_interpolation.go b/applicationset/generators/value_interpolation.go
index a7b3f25b80..814843e3d8 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]any, useGoTemplate bool, goTemplateOptions []string) error {
+func appendTemplatedValues(values map[string]string, params map[string]interface{}, 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]any{}
+ tmp := map[string]interface{}{}
for key, value := range values {
result, err := replaceTemplatedString(value, params, useGoTemplate, goTemplateOptions)
@@ -22,7 +22,7 @@ func appendTemplatedValues(values map[string]string, params map[string]any, useG
}
tmp["values"].(map[string]string)[key] = result
} else {
- tmp["values."+key] = result
+ tmp[fmt.Sprintf("values.%s", key)] = result
}
}
@@ -33,7 +33,7 @@ func appendTemplatedValues(values map[string]string, params map[string]any, useG
return nil
}
-func replaceTemplatedString(value string, params map[string]any, useGoTemplate bool, goTemplateOptions []string) (string, error) {
+func replaceTemplatedString(value string, params map[string]interface{}, 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 38a4bfd167..5b490233d5 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]any
- expected map[string]any
+ params map[string]interface{}
+ expected map[string]interface{}
}{
{
name: "Simple interpolation",
values: map[string]string{
"hello": "{{ world }}",
},
- params: map[string]any{
+ params: map[string]interface{}{
"world": "world!",
},
- expected: map[string]any{
+ expected: map[string]interface{}{
"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]any{},
- expected: map[string]any{
+ params: map[string]interface{}{},
+ expected: map[string]interface{}{
"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]any{},
- expected: map[string]any{
+ params: map[string]interface{}{},
+ expected: map[string]interface{}{
"values.lol1": "lol",
"values.lol2": "{{values.lol1}}{{values.lol1}}",
"values.lol3": "{{values.lol2}}{{values.lol2}}{{values.lol2}}",
@@ -57,7 +57,7 @@ func TestValueInterpolation(t *testing.T) {
t.Run(testCase.name, func(t *testing.T) {
err := appendTemplatedValues(testCase.values, testCase.params, false, nil)
require.NoError(t, err)
- assert.Equal(t, testCase.expected, testCase.params)
+ assert.EqualValues(t, testCase.expected, testCase.params)
})
}
}
@@ -66,18 +66,18 @@ func TestValueInterpolationWithGoTemplating(t *testing.T) {
testCases := []struct {
name string
values map[string]string
- params map[string]any
- expected map[string]any
+ params map[string]interface{}
+ expected map[string]interface{}
}{
{
name: "Simple interpolation",
values: map[string]string{
"hello": "{{ .world }}",
},
- params: map[string]any{
+ params: map[string]interface{}{
"world": "world!",
},
- expected: map[string]any{
+ expected: map[string]interface{}{
"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]any{},
- expected: map[string]any{
+ params: map[string]interface{}{},
+ expected: map[string]interface{}{
"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]any{},
- expected: map[string]any{
+ params: map[string]interface{}{},
+ expected: map[string]interface{}{
"values": map[string]string{
"lol1": "lol",
"lol2": "",
@@ -118,7 +118,7 @@ func TestValueInterpolationWithGoTemplating(t *testing.T) {
t.Run(testCase.name, func(t *testing.T) {
err := appendTemplatedValues(testCase.values, testCase.params, true, nil)
require.NoError(t, err)
- assert.Equal(t, testCase.expected, testCase.params)
+ assert.EqualValues(t, testCase.expected, testCase.params)
})
}
}
diff --git a/applicationset/metrics/fake.go b/applicationset/metrics/fake.go
index aebddde651..9c1d55d2f2 100644
--- a/applicationset/metrics/fake.go
+++ b/applicationset/metrics/fake.go
@@ -2,10 +2,11 @@ package metrics
import (
"github.com/prometheus/client_golang/prometheus"
+ ctrlclient "sigs.k8s.io/controller-runtime/pkg/client"
)
// Fake implementation for testing
-func NewFakeAppsetMetrics() *ApplicationsetMetrics {
+func NewFakeAppsetMetrics(client ctrlclient.WithWatch) *ApplicationsetMetrics {
reconcileHistogram := prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Name: "argocd_appset_reconcile",
diff --git a/applicationset/metrics/metrics.go b/applicationset/metrics/metrics.go
index b50e359f31..5b5c1cd82c 100644
--- a/applicationset/metrics/metrics.go
+++ b/applicationset/metrics/metrics.go
@@ -7,10 +7,9 @@ import (
"k8s.io/apimachinery/pkg/labels"
"sigs.k8s.io/controller-runtime/pkg/metrics"
- argoappv1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- applisters "github.com/argoproj/argo-cd/v3/pkg/client/listers/application/v1alpha1"
- metricsutil "github.com/argoproj/argo-cd/v3/util/metrics"
- "github.com/argoproj/argo-cd/v3/util/metrics/kubectl"
+ argoappv1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+ applisters "github.com/argoproj/argo-cd/v2/pkg/client/listers/application/v1alpha1"
+ metricsutil "github.com/argoproj/argo-cd/v2/util/metrics"
)
var (
@@ -58,10 +57,6 @@ func NewApplicationsetMetrics(appsetLister applisters.ApplicationSetLister, apps
metrics.Registry.MustRegister(reconcileHistogram)
metrics.Registry.MustRegister(appsetCollector)
- kubectlMetricsServer := kubectl.NewKubectlMetrics()
- kubectlMetricsServer.RegisterWithClientGo()
- kubectl.RegisterWithPrometheus(metrics.Registry)
-
return ApplicationsetMetrics{
reconcileHistogram: reconcileHistogram,
}
diff --git a/applicationset/metrics/metrics_test.go b/applicationset/metrics/metrics_test.go
index 1db5b3efbe..13457ca03d 100644
--- a/applicationset/metrics/metrics_test.go
+++ b/applicationset/metrics/metrics_test.go
@@ -7,19 +7,23 @@ import (
"testing"
"time"
- "github.com/prometheus/client_golang/prometheus"
+ "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/promhttp"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"k8s.io/apimachinery/pkg/runtime"
ctrlclient "sigs.k8s.io/controller-runtime/pkg/client"
- "sigs.k8s.io/controller-runtime/pkg/client/fake"
- "sigs.k8s.io/controller-runtime/pkg/metrics"
- "sigs.k8s.io/yaml"
+ fake "sigs.k8s.io/controller-runtime/pkg/client/fake"
- "github.com/argoproj/argo-cd/v3/applicationset/utils"
- argoappv1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- metricsutil "github.com/argoproj/argo-cd/v3/util/metrics"
+ prometheus "github.com/prometheus/client_golang/prometheus"
+
+ metricsutil "github.com/argoproj/argo-cd/v2/util/metrics"
+
+ "sigs.k8s.io/controller-runtime/pkg/metrics"
+
+ "sigs.k8s.io/yaml"
)
var (
diff --git a/applicationset/services/internal/github_app/client.go b/applicationset/services/internal/github_app/client.go
index df96ba1731..7cdfd51554 100644
--- a/applicationset/services/internal/github_app/client.go
+++ b/applicationset/services/internal/github_app/client.go
@@ -5,9 +5,9 @@ import (
"net/http"
"github.com/bradleyfalzon/ghinstallation/v2"
- "github.com/google/go-github/v69/github"
+ "github.com/google/go-github/v66/github"
- "github.com/argoproj/argo-cd/v3/applicationset/services/github_app_auth"
+ "github.com/argoproj/argo-cd/v2/applicationset/services/github_app_auth"
)
// Client builds a github client for the given app authentication.
diff --git a/applicationset/services/internal/http/client.go b/applicationset/services/internal/http/client.go
index b16bd873e6..1a4a86285a 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) NewRequestWithContext(ctx context.Context, method, path string, body any) (*http.Request, error) {
+func (c *Client) NewRequest(method, path string, body interface{}, options []ClientOptionFunc) (*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) NewRequestWithContext(ctx context.Context, method, path string,
}
}
- req, err := http.NewRequestWithContext(ctx, method, c.baseURL+path, buf)
+ req, err := http.NewRequest(method, c.baseURL+path, buf)
if err != nil {
return nil, err
}
@@ -102,7 +102,7 @@ func (c *Client) NewRequestWithContext(ctx context.Context, method, path string,
return req, nil
}
-func (c *Client) Do(req *http.Request, v any) (*http.Response, error) {
+func (c *Client) Do(ctx context.Context, req *http.Request, v interface{}) (*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]any
+ var raw map[string]interface{}
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 c0235cd74d..29c183b5b2 100644
--- a/applicationset/services/internal/http/client_test.go
+++ b/applicationset/services/internal/http/client_test.go
@@ -2,7 +2,7 @@ package http
import (
"bytes"
- "errors"
+ "context"
"fmt"
"io"
"net/http"
@@ -14,7 +14,7 @@ import (
)
func TestClient(t *testing.T) {
- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, err := w.Write([]byte("Hello, World!"))
if err != nil {
@@ -29,13 +29,15 @@ func TestClient(t *testing.T) {
}
func TestClientDo(t *testing.T) {
+ ctx := context.Background()
+
for _, c := range []struct {
name string
params map[string]string
content []byte
fakeServer *httptest.Server
clientOptionFns []ClientOptionFunc
- expected []map[string]any
+ expected []map[string]interface{}
expectedCode int
expectedError error
}{
@@ -45,7 +47,7 @@ func TestClientDo(t *testing.T) {
"pkey1": "val1",
"pkey2": "val2",
},
- fakeServer: httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ fakeServer: httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, err := w.Write([]byte(`[{
"key1": "val1",
@@ -62,12 +64,12 @@ func TestClientDo(t *testing.T) {
}
})),
clientOptionFns: nil,
- expected: []map[string]any{
+ expected: []map[string]interface{}{
{
"key1": "val1",
- "key2": map[string]any{
+ "key2": map[string]interface{}{
"key2_1": "val2_1",
- "key2_2": map[string]any{
+ "key2_2": map[string]interface{}{
"key2_2_1": "val2_2_1",
},
},
@@ -105,9 +107,9 @@ func TestClientDo(t *testing.T) {
}
})),
clientOptionFns: nil,
- expected: []map[string]any(nil),
+ expected: []map[string]interface{}(nil),
expectedCode: http.StatusUnauthorized,
- expectedError: errors.New("API error with status code 401: "),
+ expectedError: fmt.Errorf("API error with status code 401: "),
},
} {
cc := c
@@ -117,12 +119,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.NewRequestWithContext(t.Context(), http.MethodPost, "", cc.params)
+ req, err := client.NewRequest("POST", "", cc.params, nil)
require.NoError(t, err, "NewRequest returned unexpected error")
- var data []map[string]any
+ var data []map[string]interface{}
- resp, err := client.Do(req, &data)
+ resp, err := client.Do(ctx, req, &data)
if cc.expectedError != nil {
assert.EqualError(t, err, cc.expectedError.Error())
diff --git a/applicationset/services/mocks/Repos.go b/applicationset/services/mocks/Repos.go
index d493bf2da7..7d67fe4ab2 100644
--- a/applicationset/services/mocks/Repos.go
+++ b/applicationset/services/mocks/Repos.go
@@ -1,15 +1,78 @@
-// Code generated by mockery; DO NOT EDIT.
-// github.com/vektra/mockery
-// template: testify
+// Code generated by mockery v2.53.4. DO NOT EDIT.
package mocks
import (
- "context"
+ context "context"
mock "github.com/stretchr/testify/mock"
)
+// Repos is an autogenerated mock type for the Repos type
+type Repos struct {
+ mock.Mock
+}
+
+// GetDirectories provides a mock function with given fields: ctx, repoURL, revision, noRevisionCache, verifyCommit
+func (_m *Repos) GetDirectories(ctx context.Context, repoURL string, revision string, noRevisionCache bool, verifyCommit bool) ([]string, error) {
+ ret := _m.Called(ctx, repoURL, revision, noRevisionCache, verifyCommit)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetDirectories")
+ }
+
+ var r0 []string
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, string, string, bool, bool) ([]string, error)); ok {
+ return rf(ctx, repoURL, revision, noRevisionCache, verifyCommit)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, string, string, bool, bool) []string); ok {
+ r0 = rf(ctx, repoURL, revision, noRevisionCache, verifyCommit)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).([]string)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, string, string, bool, bool) error); ok {
+ r1 = rf(ctx, repoURL, revision, noRevisionCache, verifyCommit)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetFiles provides a mock function with given fields: ctx, repoURL, revision, pattern, noRevisionCache, verifyCommit
+func (_m *Repos) GetFiles(ctx context.Context, repoURL string, revision string, pattern string, noRevisionCache bool, verifyCommit bool) (map[string][]byte, error) {
+ ret := _m.Called(ctx, repoURL, revision, pattern, noRevisionCache, verifyCommit)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetFiles")
+ }
+
+ var r0 map[string][]byte
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, string, string, string, bool, bool) (map[string][]byte, error)); ok {
+ return rf(ctx, repoURL, revision, pattern, noRevisionCache, verifyCommit)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, string, string, string, bool, bool) map[string][]byte); ok {
+ r0 = rf(ctx, repoURL, revision, pattern, noRevisionCache, verifyCommit)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(map[string][]byte)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, string, string, string, bool, bool) error); ok {
+ r1 = rf(ctx, repoURL, revision, pattern, noRevisionCache, verifyCommit)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
// NewRepos creates a new instance of Repos. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
// The first argument is typically a *testing.T value.
func NewRepos(t interface {
@@ -23,139 +86,3 @@ func NewRepos(t interface {
return mock
}
-
-// Repos is an autogenerated mock type for the Repos type
-type Repos struct {
- mock.Mock
-}
-
-type Repos_Expecter struct {
- mock *mock.Mock
-}
-
-func (_m *Repos) EXPECT() *Repos_Expecter {
- return &Repos_Expecter{mock: &_m.Mock}
-}
-
-// GetDirectories provides a mock function for the type Repos
-func (_mock *Repos) GetDirectories(ctx context.Context, repoURL string, revision string, project string, noRevisionCache bool, verifyCommit bool) ([]string, error) {
- ret := _mock.Called(ctx, repoURL, revision, project, noRevisionCache, verifyCommit)
-
- if len(ret) == 0 {
- panic("no return value specified for GetDirectories")
- }
-
- var r0 []string
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, string, string, string, bool, bool) ([]string, error)); ok {
- return returnFunc(ctx, repoURL, revision, project, noRevisionCache, verifyCommit)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, string, string, string, bool, bool) []string); ok {
- r0 = returnFunc(ctx, repoURL, revision, project, noRevisionCache, verifyCommit)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).([]string)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, string, string, string, bool, bool) error); ok {
- r1 = returnFunc(ctx, repoURL, revision, project, noRevisionCache, verifyCommit)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Repos_GetDirectories_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetDirectories'
-type Repos_GetDirectories_Call struct {
- *mock.Call
-}
-
-// GetDirectories is a helper method to define mock.On call
-// - ctx
-// - repoURL
-// - revision
-// - project
-// - noRevisionCache
-// - verifyCommit
-func (_e *Repos_Expecter) GetDirectories(ctx interface{}, repoURL interface{}, revision interface{}, project interface{}, noRevisionCache interface{}, verifyCommit interface{}) *Repos_GetDirectories_Call {
- return &Repos_GetDirectories_Call{Call: _e.mock.On("GetDirectories", ctx, repoURL, revision, project, noRevisionCache, verifyCommit)}
-}
-
-func (_c *Repos_GetDirectories_Call) Run(run func(ctx context.Context, repoURL string, revision string, project string, noRevisionCache bool, verifyCommit bool)) *Repos_GetDirectories_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(string), args[2].(string), args[3].(string), args[4].(bool), args[5].(bool))
- })
- return _c
-}
-
-func (_c *Repos_GetDirectories_Call) Return(strings []string, err error) *Repos_GetDirectories_Call {
- _c.Call.Return(strings, err)
- return _c
-}
-
-func (_c *Repos_GetDirectories_Call) RunAndReturn(run func(ctx context.Context, repoURL string, revision string, project string, noRevisionCache bool, verifyCommit bool) ([]string, error)) *Repos_GetDirectories_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetFiles provides a mock function for the type Repos
-func (_mock *Repos) GetFiles(ctx context.Context, repoURL string, revision string, project string, pattern string, noRevisionCache bool, verifyCommit bool) (map[string][]byte, error) {
- ret := _mock.Called(ctx, repoURL, revision, project, pattern, noRevisionCache, verifyCommit)
-
- if len(ret) == 0 {
- panic("no return value specified for GetFiles")
- }
-
- var r0 map[string][]byte
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, string, string, string, string, bool, bool) (map[string][]byte, error)); ok {
- return returnFunc(ctx, repoURL, revision, project, pattern, noRevisionCache, verifyCommit)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, string, string, string, string, bool, bool) map[string][]byte); ok {
- r0 = returnFunc(ctx, repoURL, revision, project, pattern, noRevisionCache, verifyCommit)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(map[string][]byte)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, string, string, string, string, bool, bool) error); ok {
- r1 = returnFunc(ctx, repoURL, revision, project, pattern, noRevisionCache, verifyCommit)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Repos_GetFiles_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetFiles'
-type Repos_GetFiles_Call struct {
- *mock.Call
-}
-
-// GetFiles is a helper method to define mock.On call
-// - ctx
-// - repoURL
-// - revision
-// - project
-// - pattern
-// - noRevisionCache
-// - verifyCommit
-func (_e *Repos_Expecter) GetFiles(ctx interface{}, repoURL interface{}, revision interface{}, project interface{}, pattern interface{}, noRevisionCache interface{}, verifyCommit interface{}) *Repos_GetFiles_Call {
- return &Repos_GetFiles_Call{Call: _e.mock.On("GetFiles", ctx, repoURL, revision, project, pattern, noRevisionCache, verifyCommit)}
-}
-
-func (_c *Repos_GetFiles_Call) Run(run func(ctx context.Context, repoURL string, revision string, project string, pattern string, noRevisionCache bool, verifyCommit bool)) *Repos_GetFiles_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(string), args[2].(string), args[3].(string), args[4].(string), args[5].(bool), args[6].(bool))
- })
- return _c
-}
-
-func (_c *Repos_GetFiles_Call) Return(stringToBytes map[string][]byte, err error) *Repos_GetFiles_Call {
- _c.Call.Return(stringToBytes, err)
- return _c
-}
-
-func (_c *Repos_GetFiles_Call) RunAndReturn(run func(ctx context.Context, repoURL string, revision string, project string, pattern string, noRevisionCache bool, verifyCommit bool) (map[string][]byte, error)) *Repos_GetFiles_Call {
- _c.Call.Return(run)
- return _c
-}
diff --git a/applicationset/services/plugin/plugin_service.go b/applicationset/services/plugin/plugin_service.go
index b88e4ea30b..175683c434 100644
--- a/applicationset/services/plugin/plugin_service.go
+++ b/applicationset/services/plugin/plugin_service.go
@@ -5,8 +5,8 @@ import (
"fmt"
"net/http"
- internalhttp "github.com/argoproj/argo-cd/v3/applicationset/services/internal/http"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ internalhttp "github.com/argoproj/argo-cd/v2/applicationset/services/internal/http"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
)
// ServiceRequest is the request object sent to the plugin service.
@@ -20,7 +20,7 @@ type ServiceRequest struct {
type Output struct {
// Parameters is the list of parameter sets returned by the plugin.
- Parameters []map[string]any `json:"parameters"`
+ Parameters []map[string]interface{} `json:"parameters"`
}
// ServiceResponse is the response object returned by the plugin service.
@@ -34,7 +34,7 @@ type Service struct {
appSetName string
}
-func NewPluginService(appSetName string, baseURL string, token string, requestTimeout int) (*Service, error) {
+func NewPluginService(ctx context.Context, 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(appSetName string, baseURL string, token string, requestTi
}
func (p *Service) List(ctx context.Context, parameters v1alpha1.PluginParameters) (*ServiceResponse, error) {
- req, err := p.client.NewRequestWithContext(ctx, http.MethodPost, "api/v1/getparams.execute", ServiceRequest{ApplicationSetName: p.appSetName, Input: v1alpha1.PluginInput{Parameters: parameters}})
+ req, err := p.client.NewRequest(http.MethodPost, "api/v1/getparams.execute", ServiceRequest{ApplicationSetName: p.appSetName, Input: v1alpha1.PluginInput{Parameters: parameters}}, nil)
if err != nil {
return nil, fmt.Errorf("NewRequest returned unexpected error: %w", err)
}
var data ServiceResponse
- _, err = p.client.Do(req, &data)
+ _, err = p.client.Do(ctx, 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 a04841203f..c6e795c403 100644
--- a/applicationset/services/plugin/plugin_service_test.go
+++ b/applicationset/services/plugin/plugin_service_test.go
@@ -1,6 +1,7 @@
package plugin
import (
+ "context"
"encoding/json"
"fmt"
"net/http"
@@ -30,10 +31,10 @@ func TestPlugin(t *testing.T) {
ts := httptest.NewServer(handler)
defer ts.Close()
- client, err := NewPluginService("plugin-test", ts.URL, token, 0)
+ client, err := NewPluginService(context.Background(), "plugin-test", ts.URL, token, 0)
require.NoError(t, err)
- data, err := client.List(t.Context(), nil)
+ data, err := client.List(context.Background(), nil)
require.NoError(t, err)
var expectedData ServiceResponse
diff --git a/applicationset/services/plugin/utils.go b/applicationset/services/plugin/utils.go
index 7130f748b6..26e38e4922 100644
--- a/applicationset/services/plugin/utils.go
+++ b/applicationset/services/plugin/utils.go
@@ -1,9 +1,10 @@
package plugin
import (
+ "fmt"
"strings"
- "github.com/argoproj/argo-cd/v3/common"
+ "github.com/argoproj/argo-cd/v2/common"
)
// ParseSecretKey retrieves secret appSetName if different from common ArgoCDSecretName.
@@ -11,7 +12,7 @@ func ParseSecretKey(key string) (secretName string, tokenKey string) {
if strings.Contains(key, ":") {
parts := strings.Split(key, ":")
secretName = parts[0][1:]
- tokenKey = "$" + parts[1]
+ tokenKey = fmt.Sprintf("$%s", parts[1])
} else {
secretName = common.ArgoCDSecretName
tokenKey = key
diff --git a/applicationset/services/pull_request/azure_devops.go b/applicationset/services/pull_request/azure_devops.go
index f70d2eda13..1d263212cd 100644
--- a/applicationset/services/pull_request/azure_devops.go
+++ b/applicationset/services/pull_request/azure_devops.go
@@ -5,9 +5,9 @@ import (
"fmt"
"strings"
- "github.com/microsoft/azure-devops-go-api/azuredevops/v7"
- "github.com/microsoft/azure-devops-go-api/azuredevops/v7/core"
- "github.com/microsoft/azure-devops-go-api/azuredevops/v7/git"
+ "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"
)
const AZURE_DEVOPS_DEFAULT_URL = "https://dev.azure.com"
@@ -41,14 +41,14 @@ var (
_ AzureDevOpsClientFactory = &devopsFactoryImpl{}
)
-func NewAzureDevOpsService(token, url, organization, project, repo string, labels []string) (PullRequestService, error) {
- organizationURL := buildURL(url, organization)
+func NewAzureDevOpsService(ctx context.Context, token, url, organization, project, repo string, labels []string) (PullRequestService, error) {
+ organizationUrl := buildURL(url, organization)
var connection *azuredevops.Connection
if token == "" {
- connection = azuredevops.NewAnonymousConnection(organizationURL)
+ connection = azuredevops.NewAnonymousConnection(organizationUrl)
} else {
- connection = azuredevops.NewPatConnection(organizationURL, token)
+ connection = azuredevops.NewPatConnection(organizationUrl, token)
}
return &AzureDevOpsService{
diff --git a/applicationset/services/pull_request/azure_devops_test.go b/applicationset/services/pull_request/azure_devops_test.go
index 29774ad08e..24453c93a2 100644
--- a/applicationset/services/pull_request/azure_devops_test.go
+++ b/applicationset/services/pull_request/azure_devops_test.go
@@ -4,14 +4,15 @@ import (
"context"
"testing"
- "github.com/microsoft/azure-devops-go-api/azuredevops/v7/core"
- "github.com/microsoft/azure-devops-go-api/azuredevops/v7/git"
- "github.com/microsoft/azure-devops-go-api/azuredevops/v7/webapi"
+ "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/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
- azureMock "github.com/argoproj/argo-cd/v3/applicationset/services/scm_provider/azure_devops/git/mocks"
+ azureMock "github.com/argoproj/argo-cd/v2/applicationset/services/scm_provider/azure_devops/git/mocks"
)
func createBoolPtr(x bool) *bool {
@@ -60,20 +61,20 @@ func (m *AzureClientFactoryMock) GetClient(ctx context.Context) (git.Client, err
func TestListPullRequest(t *testing.T) {
teamProject := "myorg_project"
repoName := "myorg_project_repo"
- prID := 123
- prTitle := "feat(123)"
- prHeadSha := "cd4973d9d14a08ffe6b641a89a68891d6aac8056"
- ctx := t.Context()
+ pr_id := 123
+ pr_title := "feat(123)"
+ pr_head_sha := "cd4973d9d14a08ffe6b641a89a68891d6aac8056"
+ ctx := context.Background()
uniqueName := "testName"
pullRequestMock := []git.GitPullRequest{
{
- PullRequestId: createIntPtr(prID),
- Title: createStringPtr(prTitle),
+ PullRequestId: createIntPtr(pr_id),
+ Title: createStringPtr(pr_title),
SourceRefName: createStringPtr("refs/heads/feature-branch"),
TargetRefName: createStringPtr("refs/heads/main"),
LastMergeSourceCommit: &git.GitCommitRef{
- CommitId: createStringPtr(prHeadSha),
+ CommitId: createStringPtr(pr_head_sha),
},
Labels: &[]core.WebApiTagDefinition{},
Repository: &git.GitRepository{
@@ -107,9 +108,9 @@ func TestListPullRequest(t *testing.T) {
assert.Len(t, list, 1)
assert.Equal(t, "feature-branch", list[0].Branch)
assert.Equal(t, "main", list[0].TargetBranch)
- assert.Equal(t, prHeadSha, list[0].HeadSHA)
+ assert.Equal(t, pr_head_sha, list[0].HeadSHA)
assert.Equal(t, "feat(123)", list[0].Title)
- assert.Equal(t, prID, list[0].Number)
+ assert.Equal(t, pr_id, list[0].Number)
assert.Equal(t, uniqueName, list[0].Author)
}
diff --git a/applicationset/services/pull_request/bitbucket_cloud.go b/applicationset/services/pull_request/bitbucket_cloud.go
index 1d03bb0249..2ee79d2cfa 100644
--- a/applicationset/services/pull_request/bitbucket_cloud.go
+++ b/applicationset/services/pull_request/bitbucket_cloud.go
@@ -3,7 +3,6 @@ package pull_request
import (
"context"
"encoding/json"
- "errors"
"fmt"
"net/url"
@@ -17,19 +16,10 @@ type BitbucketCloudService struct {
}
type BitbucketCloudPullRequest struct {
- ID int `json:"id"`
- Title string `json:"title"`
- Source BitbucketCloudPullRequestSource `json:"source"`
- Author BitbucketCloudPullRequestAuthor `json:"author"`
- Destination BitbucketCloudPullRequestDestination `json:"destination"`
-}
-
-type BitbucketCloudPullRequestDestination struct {
- Branch BitbucketCloudPullRequestDestinationBranch `json:"branch"`
-}
-
-type BitbucketCloudPullRequestDestinationBranch struct {
- Name string `json:"name"`
+ ID int `json:"id"`
+ Title string `json:"title"`
+ Source BitbucketCloudPullRequestSource `json:"source"`
+ Author BitbucketCloudPullRequestAuthor `json:"author"`
}
type BitbucketCloudPullRequestSource struct {
@@ -61,7 +51,7 @@ type PullRequestResponse struct {
var _ PullRequestService = (*BitbucketCloudService)(nil)
-func parseURL(uri string) (*url.URL, error) {
+func parseUrl(uri string) (*url.URL, error) {
if uri == "" {
uri = "https://api.bitbucket.org/2.0"
}
@@ -74,10 +64,10 @@ func parseURL(uri string) (*url.URL, error) {
return url, nil
}
-func NewBitbucketCloudServiceBasicAuth(baseURL, username, password, owner, repositorySlug string) (PullRequestService, error) {
- url, err := parseURL(baseURL)
+func NewBitbucketCloudServiceBasicAuth(baseUrl, username, password, owner, repositorySlug string) (PullRequestService, error) {
+ url, err := parseUrl(baseUrl)
if err != nil {
- return nil, fmt.Errorf("error parsing base url of %s for %s/%s: %w", baseURL, owner, repositorySlug, err)
+ return nil, fmt.Errorf("error parsing base url of %s for %s/%s: %w", baseUrl, owner, repositorySlug, err)
}
bitbucketClient := bitbucket.NewBasicAuth(username, password)
@@ -90,10 +80,10 @@ func NewBitbucketCloudServiceBasicAuth(baseURL, username, password, owner, repos
}, nil
}
-func NewBitbucketCloudServiceBearerToken(baseURL, bearerToken, owner, repositorySlug string) (PullRequestService, error) {
- url, err := parseURL(baseURL)
+func NewBitbucketCloudServiceBearerToken(baseUrl, bearerToken, owner, repositorySlug string) (PullRequestService, error) {
+ url, err := parseUrl(baseUrl)
if err != nil {
- return nil, fmt.Errorf("error parsing base url of %s for %s/%s: %w", baseURL, owner, repositorySlug, err)
+ return nil, fmt.Errorf("error parsing base url of %s for %s/%s: %w", baseUrl, owner, repositorySlug, err)
}
bitbucketClient := bitbucket.NewOAuthbearerToken(bearerToken)
@@ -106,9 +96,9 @@ func NewBitbucketCloudServiceBearerToken(baseURL, bearerToken, owner, repository
}, nil
}
-func NewBitbucketCloudServiceNoAuth(baseURL, owner, repositorySlug string) (PullRequestService, error) {
+func NewBitbucketCloudServiceNoAuth(baseUrl, owner, repositorySlug string) (PullRequestService, error) {
// There is currently no method to explicitly not require auth
- return NewBitbucketCloudServiceBearerToken(baseURL, "", owner, repositorySlug)
+ return NewBitbucketCloudServiceBearerToken(baseUrl, "", owner, repositorySlug)
}
func (b *BitbucketCloudService) List(_ context.Context) ([]*PullRequest, error) {
@@ -122,14 +112,14 @@ 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]any)
+ resp, ok := response.(map[string]interface{})
if !ok {
- return nil, errors.New("unknown type returned from bitbucket pull requests")
+ return nil, fmt.Errorf("unknown type returned from bitbucket pull requests")
}
- repoArray, ok := resp["values"].([]any)
+ repoArray, ok := resp["values"].([]interface{})
if !ok {
- return nil, errors.New("unknown type returned from response values")
+ return nil, fmt.Errorf("unknown type returned from response values")
}
jsonStr, err := json.Marshal(repoArray)
@@ -145,12 +135,11 @@ func (b *BitbucketCloudService) List(_ context.Context) ([]*PullRequest, error)
pullRequests := []*PullRequest{}
for _, pull := range pulls {
pullRequests = append(pullRequests, &PullRequest{
- Number: pull.ID,
- Title: pull.Title,
- Branch: pull.Source.Branch.Name,
- TargetBranch: pull.Destination.Branch.Name,
- HeadSHA: pull.Source.Commit.Hash,
- Author: pull.Author.Nickname,
+ Number: pull.ID,
+ Title: pull.Title,
+ Branch: pull.Source.Branch.Name,
+ HeadSHA: pull.Source.Commit.Hash,
+ Author: pull.Author.Nickname,
})
}
diff --git a/applicationset/services/pull_request/bitbucket_cloud_test.go b/applicationset/services/pull_request/bitbucket_cloud_test.go
index 62a949bf80..411f6148c8 100644
--- a/applicationset/services/pull_request/bitbucket_cloud_test.go
+++ b/applicationset/services/pull_request/bitbucket_cloud_test.go
@@ -1,6 +1,7 @@
package pull_request
import (
+ "context"
"fmt"
"io"
"net/http"
@@ -10,7 +11,7 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
)
func defaultHandlerCloud(t *testing.T) func(http.ResponseWriter, *http.Request) {
@@ -53,11 +54,11 @@ func defaultHandlerCloud(t *testing.T) func(http.ResponseWriter, *http.Request)
}
func TestParseUrlEmptyUrl(t *testing.T) {
- url, err := parseURL("")
- bitbucketURL, _ := url.Parse("https://api.bitbucket.org/2.0")
+ url, err := parseUrl("")
+ bitbucketUrl, _ := url.Parse("https://api.bitbucket.org/2.0")
require.NoError(t, err)
- assert.Equal(t, bitbucketURL, url)
+ assert.Equal(t, bitbucketUrl, url)
}
func TestInvalidBaseUrlBasicAuthCloud(t *testing.T) {
@@ -86,7 +87,7 @@ func TestListPullRequestBearerTokenCloud(t *testing.T) {
defer ts.Close()
svc, err := NewBitbucketCloudServiceBearerToken(ts.URL, "TOKEN", "OWNER", "REPO")
require.NoError(t, err)
- pullRequests, err := ListPullRequests(t.Context(), svc, []v1alpha1.PullRequestGeneratorFilter{})
+ pullRequests, err := ListPullRequests(context.Background(), svc, []v1alpha1.PullRequestGeneratorFilter{})
require.NoError(t, err)
assert.Len(t, pullRequests, 1)
assert.Equal(t, 101, pullRequests[0].Number)
@@ -104,7 +105,7 @@ func TestListPullRequestNoAuthCloud(t *testing.T) {
defer ts.Close()
svc, err := NewBitbucketCloudServiceNoAuth(ts.URL, "OWNER", "REPO")
require.NoError(t, err)
- pullRequests, err := ListPullRequests(t.Context(), svc, []v1alpha1.PullRequestGeneratorFilter{})
+ pullRequests, err := ListPullRequests(context.Background(), svc, []v1alpha1.PullRequestGeneratorFilter{})
require.NoError(t, err)
assert.Len(t, pullRequests, 1)
assert.Equal(t, 101, pullRequests[0].Number)
@@ -122,7 +123,7 @@ func TestListPullRequestBasicAuthCloud(t *testing.T) {
defer ts.Close()
svc, err := NewBitbucketCloudServiceBasicAuth(ts.URL, "user", "password", "OWNER", "REPO")
require.NoError(t, err)
- pullRequests, err := ListPullRequests(t.Context(), svc, []v1alpha1.PullRequestGeneratorFilter{})
+ pullRequests, err := ListPullRequests(context.Background(), svc, []v1alpha1.PullRequestGeneratorFilter{})
require.NoError(t, err)
assert.Len(t, pullRequests, 1)
assert.Equal(t, 101, pullRequests[0].Number)
@@ -213,7 +214,7 @@ func TestListPullRequestPaginationCloud(t *testing.T) {
defer ts.Close()
svc, err := NewBitbucketCloudServiceNoAuth(ts.URL, "OWNER", "REPO")
require.NoError(t, err)
- pullRequests, err := ListPullRequests(t.Context(), svc, []v1alpha1.PullRequestGeneratorFilter{})
+ pullRequests, err := ListPullRequests(context.Background(), svc, []v1alpha1.PullRequestGeneratorFilter{})
require.NoError(t, err)
assert.Len(t, pullRequests, 3)
assert.Equal(t, PullRequest{
@@ -240,12 +241,12 @@ func TestListPullRequestPaginationCloud(t *testing.T) {
}
func TestListResponseErrorCloud(t *testing.T) {
- ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
}))
defer ts.Close()
svc, _ := NewBitbucketCloudServiceNoAuth(ts.URL, "OWNER", "REPO")
- _, err := ListPullRequests(t.Context(), svc, []v1alpha1.PullRequestGeneratorFilter{})
+ _, err := ListPullRequests(context.Background(), svc, []v1alpha1.PullRequestGeneratorFilter{})
require.Error(t, err)
}
@@ -269,7 +270,7 @@ func TestListResponseMalformedCloud(t *testing.T) {
}))
defer ts.Close()
svc, _ := NewBitbucketCloudServiceNoAuth(ts.URL, "OWNER", "REPO")
- _, err := ListPullRequests(t.Context(), svc, []v1alpha1.PullRequestGeneratorFilter{})
+ _, err := ListPullRequests(context.Background(), svc, []v1alpha1.PullRequestGeneratorFilter{})
require.Error(t, err)
}
@@ -293,7 +294,7 @@ func TestListResponseMalformedValuesCloud(t *testing.T) {
}))
defer ts.Close()
svc, _ := NewBitbucketCloudServiceNoAuth(ts.URL, "OWNER", "REPO")
- _, err := ListPullRequests(t.Context(), svc, []v1alpha1.PullRequestGeneratorFilter{})
+ _, err := ListPullRequests(context.Background(), svc, []v1alpha1.PullRequestGeneratorFilter{})
require.Error(t, err)
}
@@ -318,7 +319,7 @@ func TestListResponseEmptyCloud(t *testing.T) {
defer ts.Close()
svc, err := NewBitbucketCloudServiceNoAuth(ts.URL, "OWNER", "REPO")
require.NoError(t, err)
- pullRequests, err := ListPullRequests(t.Context(), svc, []v1alpha1.PullRequestGeneratorFilter{})
+ pullRequests, err := ListPullRequests(context.Background(), svc, []v1alpha1.PullRequestGeneratorFilter{})
require.NoError(t, err)
assert.Empty(t, pullRequests)
}
@@ -349,11 +350,6 @@ func TestListPullRequestBranchMatchCloud(t *testing.T) {
},
"author": {
"nickname": "testName"
- },
- "destination": {
- "branch": {
- "name": "master"
- }
}
},
{
@@ -370,11 +366,6 @@ func TestListPullRequestBranchMatchCloud(t *testing.T) {
},
"author": {
"nickname": "testName"
- },
- "destination": {
- "branch": {
- "name": "branch-200"
- }
}
}
]
@@ -400,11 +391,6 @@ func TestListPullRequestBranchMatchCloud(t *testing.T) {
},
"author": {
"nickname": "testName"
- },
- "destination": {
- "branch": {
- "name": "master"
- }
}
}
]
@@ -420,7 +406,7 @@ func TestListPullRequestBranchMatchCloud(t *testing.T) {
regexp := `feature-1[\d]{2}`
svc, err := NewBitbucketCloudServiceNoAuth(ts.URL, "OWNER", "REPO")
require.NoError(t, err)
- pullRequests, err := ListPullRequests(t.Context(), svc, []v1alpha1.PullRequestGeneratorFilter{
+ pullRequests, err := ListPullRequests(context.Background(), svc, []v1alpha1.PullRequestGeneratorFilter{
{
BranchMatch: ®exp,
},
@@ -428,26 +414,24 @@ func TestListPullRequestBranchMatchCloud(t *testing.T) {
require.NoError(t, err)
assert.Len(t, pullRequests, 2)
assert.Equal(t, PullRequest{
- Number: 101,
- Title: "feat(101)",
- Branch: "feature-101",
- HeadSHA: "1a8dd249c04a",
- Author: "testName",
- TargetBranch: "master",
+ Number: 101,
+ Title: "feat(101)",
+ Branch: "feature-101",
+ HeadSHA: "1a8dd249c04a",
+ Author: "testName",
}, *pullRequests[0])
assert.Equal(t, PullRequest{
- Number: 102,
- Title: "feat(102)",
- Branch: "feature-102",
- HeadSHA: "6344d9623e3b",
- Author: "testName",
- TargetBranch: "master",
+ Number: 102,
+ Title: "feat(102)",
+ Branch: "feature-102",
+ HeadSHA: "6344d9623e3b",
+ Author: "testName",
}, *pullRequests[1])
regexp = `.*2$`
svc, err = NewBitbucketCloudServiceNoAuth(ts.URL, "OWNER", "REPO")
require.NoError(t, err)
- pullRequests, err = ListPullRequests(t.Context(), svc, []v1alpha1.PullRequestGeneratorFilter{
+ pullRequests, err = ListPullRequests(context.Background(), svc, []v1alpha1.PullRequestGeneratorFilter{
{
BranchMatch: ®exp,
},
@@ -455,40 +439,20 @@ func TestListPullRequestBranchMatchCloud(t *testing.T) {
require.NoError(t, err)
assert.Len(t, pullRequests, 1)
assert.Equal(t, PullRequest{
- Number: 102,
- Title: "feat(102)",
- Branch: "feature-102",
- HeadSHA: "6344d9623e3b",
- Author: "testName",
- TargetBranch: "master",
+ Number: 102,
+ Title: "feat(102)",
+ Branch: "feature-102",
+ HeadSHA: "6344d9623e3b",
+ Author: "testName",
}, *pullRequests[0])
regexp = `[\d{2}`
svc, err = NewBitbucketCloudServiceNoAuth(ts.URL, "OWNER", "REPO")
require.NoError(t, err)
- _, err = ListPullRequests(t.Context(), svc, []v1alpha1.PullRequestGeneratorFilter{
+ _, err = ListPullRequests(context.Background(), svc, []v1alpha1.PullRequestGeneratorFilter{
{
BranchMatch: ®exp,
},
})
require.Error(t, err)
-
- regexp = `feature-2[\d]{2}`
- targetRegexp := `branch.*`
- pullRequests, err = ListPullRequests(t.Context(), svc, []v1alpha1.PullRequestGeneratorFilter{
- {
- BranchMatch: ®exp,
- TargetBranchMatch: &targetRegexp,
- },
- })
- require.NoError(t, err)
- assert.Len(t, pullRequests, 1)
- assert.Equal(t, PullRequest{
- Number: 200,
- Title: "feat(200)",
- Branch: "feature-200",
- HeadSHA: "4cf807e67a6d",
- Author: "testName",
- TargetBranch: "branch-200",
- }, *pullRequests[0])
}
diff --git a/applicationset/services/pull_request/bitbucket_server.go b/applicationset/services/pull_request/bitbucket_server.go
index f016bba877..1f2be70edb 100644
--- a/applicationset/services/pull_request/bitbucket_server.go
+++ b/applicationset/services/pull_request/bitbucket_server.go
@@ -8,7 +8,7 @@ import (
bitbucketv1 "github.com/gfleury/go-bitbucket-v1"
log "github.com/sirupsen/logrus"
- "github.com/argoproj/argo-cd/v3/applicationset/utils"
+ "github.com/argoproj/argo-cd/v2/applicationset/utils"
)
type BitbucketService struct {
@@ -64,7 +64,7 @@ func newBitbucketService(ctx context.Context, bitbucketConfig *bitbucketv1.Confi
}
func (b *BitbucketService) List(_ context.Context) ([]*PullRequest, error) {
- paged := map[string]any{
+ paged := map[string]interface{}{
"limit": 100,
}
diff --git a/applicationset/services/pull_request/bitbucket_server_test.go b/applicationset/services/pull_request/bitbucket_server_test.go
index 745ac9f744..b9da370830 100644
--- a/applicationset/services/pull_request/bitbucket_server_test.go
+++ b/applicationset/services/pull_request/bitbucket_server_test.go
@@ -1,6 +1,7 @@
package pull_request
import (
+ "context"
"crypto/x509"
"encoding/pem"
"io"
@@ -11,7 +12,7 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
)
func defaultHandler(t *testing.T) func(http.ResponseWriter, *http.Request) {
@@ -63,9 +64,9 @@ func TestListPullRequestNoAuth(t *testing.T) {
defaultHandler(t)(w, r)
}))
defer ts.Close()
- svc, err := NewBitbucketServiceNoAuth(t.Context(), ts.URL, "PROJECT", "REPO", "", false, nil)
+ svc, err := NewBitbucketServiceNoAuth(context.Background(), ts.URL, "PROJECT", "REPO", "", false, nil)
require.NoError(t, err)
- pullRequests, err := ListPullRequests(t.Context(), svc, []v1alpha1.PullRequestGeneratorFilter{})
+ pullRequests, err := ListPullRequests(context.Background(), svc, []v1alpha1.PullRequestGeneratorFilter{})
require.NoError(t, err)
assert.Len(t, pullRequests, 1)
assert.Equal(t, 101, pullRequests[0].Number)
@@ -164,9 +165,9 @@ func TestListPullRequestPagination(t *testing.T) {
}
}))
defer ts.Close()
- svc, err := NewBitbucketServiceNoAuth(t.Context(), ts.URL, "PROJECT", "REPO", "", false, nil)
+ svc, err := NewBitbucketServiceNoAuth(context.Background(), ts.URL, "PROJECT", "REPO", "", false, nil)
require.NoError(t, err)
- pullRequests, err := ListPullRequests(t.Context(), svc, []v1alpha1.PullRequestGeneratorFilter{})
+ pullRequests, err := ListPullRequests(context.Background(), svc, []v1alpha1.PullRequestGeneratorFilter{})
require.NoError(t, err)
assert.Len(t, pullRequests, 3)
assert.Equal(t, PullRequest{
@@ -206,9 +207,9 @@ func TestListPullRequestBasicAuth(t *testing.T) {
defaultHandler(t)(w, r)
}))
defer ts.Close()
- svc, err := NewBitbucketServiceBasicAuth(t.Context(), "user", "password", ts.URL, "PROJECT", "REPO", "", false, nil)
+ svc, err := NewBitbucketServiceBasicAuth(context.Background(), "user", "password", ts.URL, "PROJECT", "REPO", "", false, nil)
require.NoError(t, err)
- pullRequests, err := ListPullRequests(t.Context(), svc, []v1alpha1.PullRequestGeneratorFilter{})
+ pullRequests, err := ListPullRequests(context.Background(), svc, []v1alpha1.PullRequestGeneratorFilter{})
require.NoError(t, err)
assert.Len(t, pullRequests, 1)
assert.Equal(t, 101, pullRequests[0].Number)
@@ -223,9 +224,9 @@ func TestListPullRequestBearerAuth(t *testing.T) {
defaultHandler(t)(w, r)
}))
defer ts.Close()
- svc, err := NewBitbucketServiceBearerToken(t.Context(), "tolkien", ts.URL, "PROJECT", "REPO", "", false, nil)
+ svc, err := NewBitbucketServiceBearerToken(context.Background(), "tolkien", ts.URL, "PROJECT", "REPO", "", false, nil)
require.NoError(t, err)
- pullRequests, err := ListPullRequests(t.Context(), svc, []v1alpha1.PullRequestGeneratorFilter{})
+ pullRequests, err := ListPullRequests(context.Background(), svc, []v1alpha1.PullRequestGeneratorFilter{})
require.NoError(t, err)
assert.Len(t, pullRequests, 1)
assert.Equal(t, 101, pullRequests[0].Number)
@@ -276,7 +277,7 @@ func TestListPullRequestTLS(t *testing.T) {
defer ts.Close()
var certs []byte
- if test.passCerts {
+ if test.passCerts == true {
for _, cert := range ts.TLS.Certificates {
for _, c := range cert.Certificate {
parsedCert, err := x509.ParseCertificate(c)
@@ -289,9 +290,9 @@ func TestListPullRequestTLS(t *testing.T) {
}
}
- svc, err := NewBitbucketServiceBasicAuth(t.Context(), "user", "password", ts.URL, "PROJECT", "REPO", "", test.tlsInsecure, certs)
+ svc, err := NewBitbucketServiceBasicAuth(context.Background(), "user", "password", ts.URL, "PROJECT", "REPO", "", test.tlsInsecure, certs)
require.NoError(t, err)
- _, err = ListPullRequests(t.Context(), svc, []v1alpha1.PullRequestGeneratorFilter{})
+ _, err = ListPullRequests(context.Background(), svc, []v1alpha1.PullRequestGeneratorFilter{})
if test.requireErr {
require.Error(t, err)
} else {
@@ -302,12 +303,12 @@ func TestListPullRequestTLS(t *testing.T) {
}
func TestListResponseError(t *testing.T) {
- ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
}))
defer ts.Close()
- svc, _ := NewBitbucketServiceNoAuth(t.Context(), ts.URL, "PROJECT", "REPO", "", false, nil)
- _, err := ListPullRequests(t.Context(), svc, []v1alpha1.PullRequestGeneratorFilter{})
+ svc, _ := NewBitbucketServiceNoAuth(context.Background(), ts.URL, "PROJECT", "REPO", "", false, nil)
+ _, err := ListPullRequests(context.Background(), svc, []v1alpha1.PullRequestGeneratorFilter{})
require.Error(t, err)
}
@@ -331,8 +332,8 @@ func TestListResponseMalformed(t *testing.T) {
}
}))
defer ts.Close()
- svc, _ := NewBitbucketServiceNoAuth(t.Context(), ts.URL, "PROJECT", "REPO", "", false, nil)
- _, err := ListPullRequests(t.Context(), svc, []v1alpha1.PullRequestGeneratorFilter{})
+ svc, _ := NewBitbucketServiceNoAuth(context.Background(), ts.URL, "PROJECT", "REPO", "", false, nil)
+ _, err := ListPullRequests(context.Background(), svc, []v1alpha1.PullRequestGeneratorFilter{})
require.Error(t, err)
}
@@ -356,9 +357,9 @@ func TestListResponseEmpty(t *testing.T) {
}
}))
defer ts.Close()
- svc, err := NewBitbucketServiceNoAuth(t.Context(), ts.URL, "PROJECT", "REPO", "", false, nil)
+ svc, err := NewBitbucketServiceNoAuth(context.Background(), ts.URL, "PROJECT", "REPO", "", false, nil)
require.NoError(t, err)
- pullRequests, err := ListPullRequests(t.Context(), svc, []v1alpha1.PullRequestGeneratorFilter{})
+ pullRequests, err := ListPullRequests(context.Background(), svc, []v1alpha1.PullRequestGeneratorFilter{})
require.NoError(t, err)
assert.Empty(t, pullRequests)
}
@@ -452,9 +453,9 @@ func TestListPullRequestBranchMatch(t *testing.T) {
}))
defer ts.Close()
regexp := `feature-1[\d]{2}`
- svc, err := NewBitbucketServiceNoAuth(t.Context(), ts.URL, "PROJECT", "REPO", "", false, nil)
+ svc, err := NewBitbucketServiceNoAuth(context.Background(), ts.URL, "PROJECT", "REPO", "", false, nil)
require.NoError(t, err)
- pullRequests, err := ListPullRequests(t.Context(), svc, []v1alpha1.PullRequestGeneratorFilter{
+ pullRequests, err := ListPullRequests(context.Background(), svc, []v1alpha1.PullRequestGeneratorFilter{
{
BranchMatch: ®exp,
},
@@ -481,9 +482,9 @@ func TestListPullRequestBranchMatch(t *testing.T) {
}, *pullRequests[1])
regexp = `.*2$`
- svc, err = NewBitbucketServiceNoAuth(t.Context(), ts.URL, "PROJECT", "REPO", "", false, nil)
+ svc, err = NewBitbucketServiceNoAuth(context.Background(), ts.URL, "PROJECT", "REPO", "", false, nil)
require.NoError(t, err)
- pullRequests, err = ListPullRequests(t.Context(), svc, []v1alpha1.PullRequestGeneratorFilter{
+ pullRequests, err = ListPullRequests(context.Background(), svc, []v1alpha1.PullRequestGeneratorFilter{
{
BranchMatch: ®exp,
},
@@ -501,9 +502,9 @@ func TestListPullRequestBranchMatch(t *testing.T) {
}, *pullRequests[0])
regexp = `[\d{2}`
- svc, err = NewBitbucketServiceNoAuth(t.Context(), ts.URL, "PROJECT", "REPO", "", false, nil)
+ svc, err = NewBitbucketServiceNoAuth(context.Background(), ts.URL, "PROJECT", "REPO", "", false, nil)
require.NoError(t, err)
- _, err = ListPullRequests(t.Context(), svc, []v1alpha1.PullRequestGeneratorFilter{
+ _, err = ListPullRequests(context.Background(), svc, []v1alpha1.PullRequestGeneratorFilter{
{
BranchMatch: ®exp,
},
diff --git a/applicationset/services/pull_request/fake.go b/applicationset/services/pull_request/fake.go
index 50d4969e84..845df70d66 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(_ context.Context) ([]*PullRequest, error) {
+func (g *FakeService) List(ctx 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 d0e51c23aa..5f32e4dc30 100644
--- a/applicationset/services/pull_request/gitea.go
+++ b/applicationset/services/pull_request/gitea.go
@@ -14,12 +14,11 @@ type GiteaService struct {
client *gitea.Client
owner string
repo string
- labels []string
}
var _ PullRequestService = (*GiteaService)(nil)
-func NewGiteaService(token, url, owner, repo string, labels []string, insecure bool) (PullRequestService, error) {
+func NewGiteaService(ctx context.Context, token, url, owner, repo string, insecure bool) (PullRequestService, error) {
if token == "" {
token = os.Getenv("GITEA_TOKEN")
}
@@ -43,7 +42,6 @@ func NewGiteaService(token, url, owner, repo string, labels []string, insecure b
client: client,
owner: owner,
repo: repo,
- labels: labels,
}, nil
}
@@ -51,16 +49,12 @@ 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
}
list := []*PullRequest{}
for _, pr := range prs {
- if !giteaContainLabels(g.labels, pr.Labels) {
- continue
- }
list = append(list, &PullRequest{
Number: int(pr.Index),
Title: pr.Title,
@@ -74,21 +68,6 @@ func (g *GiteaService) List(ctx context.Context) ([]*PullRequest, error) {
return list, nil
}
-// containLabels returns true if gotLabels contains expectedLabels
-func giteaContainLabels(expectedLabels []string, gotLabels []*gitea.Label) bool {
- gotLabelNamesMap := make(map[string]bool)
- for i := 0; i < len(gotLabels); i++ {
- gotLabelNamesMap[gotLabels[i].Name] = true
- }
- for _, expected := range expectedLabels {
- v, ok := gotLabelNamesMap[expected]
- if !v || !ok {
- return false
- }
- }
- return true
-}
-
// Get the Gitea pull request label names.
func getGiteaPRLabelNames(giteaLabels []*gitea.Label) []string {
var labelNames []string
diff --git a/applicationset/services/pull_request/gitea_test.go b/applicationset/services/pull_request/gitea_test.go
index c2b1ec22b1..ab58a049e5 100644
--- a/applicationset/services/pull_request/gitea_test.go
+++ b/applicationset/services/pull_request/gitea_test.go
@@ -1,6 +1,7 @@
package pull_request
import (
+ "context"
"fmt"
"io"
"net/http"
@@ -52,7 +53,7 @@ func giteaMockHandler(t *testing.T) func(http.ResponseWriter, *http.Request) {
},
"title": "add an empty file",
"body": "",
- "labels": [{"id": 1, "name": "label1", "color": "00aabb", "description": "foo", "url": ""}],
+ "labels": [],
"milestone": null,
"assignee": null,
"assignees": null,
@@ -246,61 +247,13 @@ func giteaMockHandler(t *testing.T) func(http.ResponseWriter, *http.Request) {
}
}
-func TestGiteaContainLabels(t *testing.T) {
- cases := []struct {
- Name string
- Labels []string
- PullLabels []*gitea.Label
- Expect bool
- }{
- {
- Name: "Match labels",
- Labels: []string{"label1", "label2"},
- PullLabels: []*gitea.Label{
- {Name: "label1"},
- {Name: "label2"},
- {Name: "label3"},
- },
- Expect: true,
- },
- {
- Name: "Not match labels",
- Labels: []string{"label1", "label4"},
- PullLabels: []*gitea.Label{
- {Name: "label1"},
- {Name: "label2"},
- {Name: "label3"},
- },
- Expect: false,
- },
- {
- Name: "No specify",
- Labels: []string{},
- PullLabels: []*gitea.Label{
- {Name: "label1"},
- {Name: "label2"},
- {Name: "label3"},
- },
- Expect: true,
- },
- }
-
- for _, c := range cases {
- t.Run(c.Name, func(t *testing.T) {
- if got := giteaContainLabels(c.Labels, c.PullLabels); got != c.Expect {
- t.Errorf("expect: %v, got: %v", c.Expect, got)
- }
- })
- }
-}
-
func TestGiteaList(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
giteaMockHandler(t)(w, r)
}))
- host, err := NewGiteaService("", ts.URL, "test-argocd", "pr-test", []string{"label1"}, false)
+ host, err := NewGiteaService(context.Background(), "", ts.URL, "test-argocd", "pr-test", false)
require.NoError(t, err)
- prs, err := host.List(t.Context())
+ prs, err := host.List(context.Background())
require.NoError(t, err)
assert.Len(t, prs, 1)
assert.Equal(t, 1, prs[0].Number)
diff --git a/applicationset/services/pull_request/github.go b/applicationset/services/pull_request/github.go
index dd63a68105..eaee02ffb1 100644
--- a/applicationset/services/pull_request/github.go
+++ b/applicationset/services/pull_request/github.go
@@ -3,10 +3,10 @@ package pull_request
import (
"context"
"fmt"
- "net/http"
"os"
- "github.com/google/go-github/v69/github"
+ "github.com/google/go-github/v66/github"
+ "golang.org/x/oauth2"
)
type GithubService struct {
@@ -18,19 +18,21 @@ type GithubService struct {
var _ PullRequestService = (*GithubService)(nil)
-func NewGithubService(token, url, owner, repo string, labels []string) (PullRequestService, error) {
+func NewGithubService(ctx context.Context, token, url, owner, repo string, labels []string) (PullRequestService, error) {
+ var ts oauth2.TokenSource
// Undocumented environment variable to set a default token, to be used in testing to dodge anonymous rate limits.
if token == "" {
token = os.Getenv("GITHUB_TOKEN")
}
- httpClient := &http.Client{}
+ if token != "" {
+ ts = oauth2.StaticTokenSource(
+ &oauth2.Token{AccessToken: token},
+ )
+ }
+ httpClient := oauth2.NewClient(ctx, ts)
var client *github.Client
if url == "" {
- if token == "" {
- client = github.NewClient(httpClient)
- } else {
- client = github.NewClient(httpClient).WithAuthToken(token)
- }
+ client = github.NewClient(httpClient)
} else {
var err error
client, err = github.NewClient(httpClient).WithEnterpriseURLs(url, url)
diff --git a/applicationset/services/pull_request/github_app.go b/applicationset/services/pull_request/github_app.go
index 3eeea1853f..8879a777ad 100644
--- a/applicationset/services/pull_request/github_app.go
+++ b/applicationset/services/pull_request/github_app.go
@@ -1,8 +1,8 @@
package pull_request
import (
- "github.com/argoproj/argo-cd/v3/applicationset/services/github_app_auth"
- "github.com/argoproj/argo-cd/v3/applicationset/services/internal/github_app"
+ "github.com/argoproj/argo-cd/v2/applicationset/services/github_app_auth"
+ "github.com/argoproj/argo-cd/v2/applicationset/services/internal/github_app"
)
func NewGithubAppService(g github_app_auth.Authentication, url, owner, repo string, labels []string) (PullRequestService, error) {
diff --git a/applicationset/services/pull_request/github_test.go b/applicationset/services/pull_request/github_test.go
index 0380891d07..fb35ad20b0 100644
--- a/applicationset/services/pull_request/github_test.go
+++ b/applicationset/services/pull_request/github_test.go
@@ -3,7 +3,7 @@ package pull_request
import (
"testing"
- "github.com/google/go-github/v69/github"
+ "github.com/google/go-github/v66/github"
"github.com/stretchr/testify/require"
)
diff --git a/applicationset/services/pull_request/gitlab.go b/applicationset/services/pull_request/gitlab.go
index d6d94cf05e..c4e49881a4 100644
--- a/applicationset/services/pull_request/gitlab.go
+++ b/applicationset/services/pull_request/gitlab.go
@@ -7,9 +7,9 @@ import (
"os"
"github.com/hashicorp/go-retryablehttp"
- gitlab "gitlab.com/gitlab-org/api/client-go"
+ gitlab "github.com/xanzy/go-gitlab"
- "github.com/argoproj/argo-cd/v3/applicationset/utils"
+ "github.com/argoproj/argo-cd/v2/applicationset/utils"
)
type GitLabService struct {
@@ -21,7 +21,7 @@ type GitLabService struct {
var _ PullRequestService = (*GitLabService)(nil)
-func NewGitLabService(token, url, project string, labels []string, pullRequestState string, scmRootCAPath string, insecure bool, caCerts []byte) (PullRequestService, error) {
+func NewGitLabService(ctx context.Context, 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, gitlab.WithContext(ctx))
+ mrs, resp, err := g.client.MergeRequests.ListProjectMergeRequests(g.project, opts)
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 ab8e99456a..18467fe088 100644
--- a/applicationset/services/pull_request/gitlab_test.go
+++ b/applicationset/services/pull_request/gitlab_test.go
@@ -1,6 +1,7 @@
package pull_request
import (
+ "context"
"crypto/x509"
"encoding/pem"
"io"
@@ -34,10 +35,10 @@ func TestGitLabServiceCustomBaseURL(t *testing.T) {
writeMRListResponse(t, w)
})
- svc, err := NewGitLabService("", server.URL, "278964", nil, "", "", false, nil)
+ svc, err := NewGitLabService(context.Background(), "", server.URL, "278964", nil, "", "", false, nil)
require.NoError(t, err)
- _, err = svc.List(t.Context())
+ _, err = svc.List(context.Background())
require.NoError(t, err)
}
@@ -53,10 +54,10 @@ func TestGitLabServiceToken(t *testing.T) {
writeMRListResponse(t, w)
})
- svc, err := NewGitLabService("token-123", server.URL, "278964", nil, "", "", false, nil)
+ svc, err := NewGitLabService(context.Background(), "token-123", server.URL, "278964", nil, "", "", false, nil)
require.NoError(t, err)
- _, err = svc.List(t.Context())
+ _, err = svc.List(context.Background())
require.NoError(t, err)
}
@@ -72,10 +73,10 @@ func TestList(t *testing.T) {
writeMRListResponse(t, w)
})
- svc, err := NewGitLabService("", server.URL, "278964", []string{}, "", "", false, nil)
+ svc, err := NewGitLabService(context.Background(), "", server.URL, "278964", []string{}, "", "", false, nil)
require.NoError(t, err)
- prs, err := svc.List(t.Context())
+ prs, err := svc.List(context.Background())
require.NoError(t, err)
assert.Len(t, prs, 1)
assert.Equal(t, 15442, prs[0].Number)
@@ -98,10 +99,10 @@ func TestListWithLabels(t *testing.T) {
writeMRListResponse(t, w)
})
- svc, err := NewGitLabService("", server.URL, "278964", []string{"feature", "ready"}, "", "", false, nil)
+ svc, err := NewGitLabService(context.Background(), "", server.URL, "278964", []string{"feature", "ready"}, "", "", false, nil)
require.NoError(t, err)
- _, err = svc.List(t.Context())
+ _, err = svc.List(context.Background())
require.NoError(t, err)
}
@@ -117,10 +118,10 @@ func TestListWithState(t *testing.T) {
writeMRListResponse(t, w)
})
- svc, err := NewGitLabService("", server.URL, "278964", []string{}, "opened", "", false, nil)
+ svc, err := NewGitLabService(context.Background(), "", server.URL, "278964", []string{}, "opened", "", false, nil)
require.NoError(t, err)
- _, err = svc.List(t.Context())
+ _, err = svc.List(context.Background())
require.NoError(t, err)
}
@@ -160,13 +161,13 @@ 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, _ *http.Request) {
+ ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
writeMRListResponse(t, w)
}))
defer ts.Close()
var certs []byte
- if test.passCerts {
+ if test.passCerts == true {
for _, cert := range ts.TLS.Certificates {
for _, c := range cert.Certificate {
parsedCert, err := x509.ParseCertificate(c)
@@ -179,10 +180,10 @@ func TestListWithStateTLS(t *testing.T) {
}
}
- svc, err := NewGitLabService("", ts.URL, "278964", []string{}, "opened", "", test.tlsInsecure, certs)
+ svc, err := NewGitLabService(context.Background(), "", ts.URL, "278964", []string{}, "opened", "", test.tlsInsecure, certs)
require.NoError(t, err)
- _, err = svc.List(t.Context())
+ _, err = svc.List(context.Background())
if test.requireErr {
require.Error(t, err)
} else {
diff --git a/applicationset/services/pull_request/utils.go b/applicationset/services/pull_request/utils.go
index 100596fc3d..09b5b6ca10 100644
--- a/applicationset/services/pull_request/utils.go
+++ b/applicationset/services/pull_request/utils.go
@@ -5,7 +5,7 @@ import (
"fmt"
"regexp"
- argoprojiov1alpha1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ argoprojiov1alpha1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
)
func compileFilters(filters []argoprojiov1alpha1.PullRequestGeneratorFilter) ([]*Filter, error) {
diff --git a/applicationset/services/pull_request/utils_test.go b/applicationset/services/pull_request/utils_test.go
index d25b25ae83..1c74ae4b66 100644
--- a/applicationset/services/pull_request/utils_test.go
+++ b/applicationset/services/pull_request/utils_test.go
@@ -1,12 +1,13 @@
package pull_request
import (
+ "context"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
- argoprojiov1alpha1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ argoprojiov1alpha1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
)
func strp(s string) *string {
@@ -15,7 +16,7 @@ func strp(s string) *string {
func TestFilterBranchMatchBadRegexp(t *testing.T) {
provider, _ := NewFakeService(
- t.Context(),
+ context.Background(),
[]*PullRequest{
{
Number: 1,
@@ -33,13 +34,13 @@ func TestFilterBranchMatchBadRegexp(t *testing.T) {
BranchMatch: strp("("),
},
}
- _, err := ListPullRequests(t.Context(), provider, filters)
+ _, err := ListPullRequests(context.Background(), provider, filters)
require.Error(t, err)
}
func TestFilterBranchMatch(t *testing.T) {
provider, _ := NewFakeService(
- t.Context(),
+ context.Background(),
[]*PullRequest{
{
Number: 1,
@@ -81,7 +82,7 @@ func TestFilterBranchMatch(t *testing.T) {
BranchMatch: strp("w"),
},
}
- pullRequests, err := ListPullRequests(t.Context(), provider, filters)
+ pullRequests, err := ListPullRequests(context.Background(), provider, filters)
require.NoError(t, err)
assert.Len(t, pullRequests, 1)
assert.Equal(t, "two", pullRequests[0].Branch)
@@ -89,7 +90,7 @@ func TestFilterBranchMatch(t *testing.T) {
func TestFilterTargetBranchMatch(t *testing.T) {
provider, _ := NewFakeService(
- t.Context(),
+ context.Background(),
[]*PullRequest{
{
Number: 1,
@@ -131,7 +132,7 @@ func TestFilterTargetBranchMatch(t *testing.T) {
TargetBranchMatch: strp("1"),
},
}
- pullRequests, err := ListPullRequests(t.Context(), provider, filters)
+ pullRequests, err := ListPullRequests(context.Background(), provider, filters)
require.NoError(t, err)
assert.Len(t, pullRequests, 1)
assert.Equal(t, "two", pullRequests[0].Branch)
@@ -139,7 +140,7 @@ func TestFilterTargetBranchMatch(t *testing.T) {
func TestMultiFilterOr(t *testing.T) {
provider, _ := NewFakeService(
- t.Context(),
+ context.Background(),
[]*PullRequest{
{
Number: 1,
@@ -184,7 +185,7 @@ func TestMultiFilterOr(t *testing.T) {
BranchMatch: strp("r"),
},
}
- pullRequests, err := ListPullRequests(t.Context(), provider, filters)
+ pullRequests, err := ListPullRequests(context.Background(), provider, filters)
require.NoError(t, err)
assert.Len(t, pullRequests, 3)
assert.Equal(t, "two", pullRequests[0].Branch)
@@ -194,7 +195,7 @@ func TestMultiFilterOr(t *testing.T) {
func TestMultiFilterOrWithTargetBranchFilter(t *testing.T) {
provider, _ := NewFakeService(
- t.Context(),
+ context.Background(),
[]*PullRequest{
{
Number: 1,
@@ -241,7 +242,7 @@ func TestMultiFilterOrWithTargetBranchFilter(t *testing.T) {
TargetBranchMatch: strp("3"),
},
}
- pullRequests, err := ListPullRequests(t.Context(), provider, filters)
+ pullRequests, err := ListPullRequests(context.Background(), provider, filters)
require.NoError(t, err)
assert.Len(t, pullRequests, 2)
assert.Equal(t, "two", pullRequests[0].Branch)
@@ -250,7 +251,7 @@ func TestMultiFilterOrWithTargetBranchFilter(t *testing.T) {
func TestNoFilters(t *testing.T) {
provider, _ := NewFakeService(
- t.Context(),
+ context.Background(),
[]*PullRequest{
{
Number: 1,
@@ -272,7 +273,7 @@ func TestNoFilters(t *testing.T) {
nil,
)
filters := []argoprojiov1alpha1.PullRequestGeneratorFilter{}
- repos, err := ListPullRequests(t.Context(), provider, filters)
+ repos, err := ListPullRequests(context.Background(), provider, filters)
require.NoError(t, err)
assert.Len(t, repos, 2)
assert.Equal(t, "one", repos[0].Branch)
diff --git a/applicationset/services/repo_service.go b/applicationset/services/repo_service.go
index dd218f3092..f415a9a6d1 100644
--- a/applicationset/services/repo_service.go
+++ b/applicationset/services/repo_service.go
@@ -4,54 +4,39 @@ import (
"context"
"fmt"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- "github.com/argoproj/argo-cd/v3/reposerver/apiclient"
- "github.com/argoproj/argo-cd/v3/util/db"
- utilio "github.com/argoproj/argo-cd/v3/util/io"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/reposerver/apiclient"
+ "github.com/argoproj/argo-cd/v2/util/git"
+ "github.com/argoproj/argo-cd/v2/util/io"
)
type argoCDService struct {
- getRepository func(ctx context.Context, url, project string) (*v1alpha1.Repository, error)
- submoduleEnabled bool
- newFileGlobbingEnabled bool
- getGitFilesFromRepoServer func(ctx context.Context, req *apiclient.GitFilesRequest) (*apiclient.GitFilesResponse, error)
- getGitDirectoriesFromRepoServer func(ctx context.Context, req *apiclient.GitDirectoriesRequest) (*apiclient.GitDirectoriesResponse, error)
+ getRepository func(ctx context.Context, url, project string) (*v1alpha1.Repository, error)
+ storecreds git.CredsStore
+ submoduleEnabled bool
+ repoServerClientSet apiclient.Clientset
+ newFileGlobbingEnabled bool
}
type Repos interface {
// GetFiles returns content of files (not directories) within the target repo
- GetFiles(ctx context.Context, repoURL, revision, project, pattern string, noRevisionCache, verifyCommit bool) (map[string][]byte, error)
+ GetFiles(ctx context.Context, repoURL string, revision string, pattern string, noRevisionCache, verifyCommit bool) (map[string][]byte, error)
// GetDirectories returns a list of directories (not files) within the target repo
- GetDirectories(ctx context.Context, repoURL, revision, project string, noRevisionCache, verifyCommit bool) ([]string, error)
+ GetDirectories(ctx context.Context, repoURL string, revision string, noRevisionCache, verifyCommit bool) ([]string, error)
}
-func NewArgoCDService(db db.ArgoDB, submoduleEnabled bool, repoClientset apiclient.Clientset, newFileGlobbingEnabled bool) Repos {
+func NewArgoCDService(getRepository func(ctx context.Context, url, project string) (*v1alpha1.Repository, error), submoduleEnabled bool, repoClientset apiclient.Clientset, newFileGlobbingEnabled bool) (Repos, error) {
return &argoCDService{
- getRepository: db.GetRepository,
+ getRepository: getRepository,
submoduleEnabled: submoduleEnabled,
+ repoServerClientSet: repoClientset,
newFileGlobbingEnabled: newFileGlobbingEnabled,
- getGitFilesFromRepoServer: func(ctx context.Context, fileRequest *apiclient.GitFilesRequest) (*apiclient.GitFilesResponse, error) {
- closer, client, err := repoClientset.NewRepoServerClient()
- if err != nil {
- return nil, fmt.Errorf("error initializing new repo server client: %w", err)
- }
- defer utilio.Close(closer)
- return client.GetGitFiles(ctx, fileRequest)
- },
- getGitDirectoriesFromRepoServer: func(ctx context.Context, dirRequest *apiclient.GitDirectoriesRequest) (*apiclient.GitDirectoriesResponse, error) {
- closer, client, err := repoClientset.NewRepoServerClient()
- if err != nil {
- return nil, fmt.Errorf("error initialising new repo server client: %w", err)
- }
- defer utilio.Close(closer)
- return client.GetGitDirectories(ctx, dirRequest)
- },
- }
+ }, nil
}
-func (a *argoCDService) GetFiles(ctx context.Context, repoURL, revision, project, pattern string, noRevisionCache, verifyCommit bool) (map[string][]byte, error) {
- repo, err := a.getRepository(ctx, repoURL, project)
+func (a *argoCDService) GetFiles(ctx context.Context, repoURL string, revision string, pattern string, noRevisionCache, verifyCommit bool) (map[string][]byte, error) {
+ repo, err := a.getRepository(ctx, repoURL, "")
if err != nil {
return nil, fmt.Errorf("error in GetRepository: %w", err)
}
@@ -65,15 +50,21 @@ func (a *argoCDService) GetFiles(ctx context.Context, repoURL, revision, project
NoRevisionCache: noRevisionCache,
VerifyCommit: verifyCommit,
}
- fileResponse, err := a.getGitFilesFromRepoServer(ctx, fileRequest)
+ closer, client, err := a.repoServerClientSet.NewRepoServerClient()
+ if err != nil {
+ return nil, fmt.Errorf("error initialising new repo server client: %w", err)
+ }
+ defer io.Close(closer)
+
+ fileResponse, err := client.GetGitFiles(ctx, fileRequest)
if err != nil {
return nil, fmt.Errorf("error retrieving Git files: %w", err)
}
return fileResponse.GetMap(), nil
}
-func (a *argoCDService) GetDirectories(ctx context.Context, repoURL, revision, project string, noRevisionCache, verifyCommit bool) ([]string, error) {
- repo, err := a.getRepository(ctx, repoURL, project)
+func (a *argoCDService) GetDirectories(ctx context.Context, repoURL string, revision string, noRevisionCache, verifyCommit bool) ([]string, error) {
+ repo, err := a.getRepository(ctx, repoURL, "")
if err != nil {
return nil, fmt.Errorf("error in GetRepository: %w", err)
}
@@ -86,7 +77,13 @@ func (a *argoCDService) GetDirectories(ctx context.Context, repoURL, revision, p
VerifyCommit: verifyCommit,
}
- dirResponse, err := a.getGitDirectoriesFromRepoServer(ctx, dirRequest)
+ closer, client, err := a.repoServerClientSet.NewRepoServerClient()
+ if err != nil {
+ return nil, fmt.Errorf("error initialising new repo server client: %w", err)
+ }
+ defer io.Close(closer)
+
+ dirResponse, err := client.GetGitDirectories(ctx, dirRequest)
if err != nil {
return nil, fmt.Errorf("error retrieving Git Directories: %w", err)
}
diff --git a/applicationset/services/repo_service_test.go b/applicationset/services/repo_service_test.go
index 4762080edd..c621c317a9 100644
--- a/applicationset/services/repo_service_test.go
+++ b/applicationset/services/repo_service_test.go
@@ -2,26 +2,26 @@ package services
import (
"context"
- "errors"
"fmt"
"testing"
"github.com/stretchr/testify/assert"
- "k8s.io/client-go/kubernetes/fake"
+ "github.com/stretchr/testify/mock"
+ "github.com/stretchr/testify/require"
- "github.com/argoproj/argo-cd/v3/reposerver/apiclient"
- repo_mocks "github.com/argoproj/argo-cd/v3/reposerver/apiclient/mocks"
- "github.com/argoproj/argo-cd/v3/util/db"
- "github.com/argoproj/argo-cd/v3/util/settings"
+ "github.com/argoproj/argo-cd/v2/reposerver/apiclient"
+ repo_mocks "github.com/argoproj/argo-cd/v2/reposerver/apiclient/mocks"
+ "github.com/argoproj/argo-cd/v2/util/git"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
)
func TestGetDirectories(t *testing.T) {
type fields struct {
- submoduleEnabled bool
- getRepository func(ctx context.Context, url, project string) (*v1alpha1.Repository, error)
- getGitDirectories func(ctx context.Context, req *apiclient.GitDirectoriesRequest) (*apiclient.GitDirectoriesResponse, error)
+ storecreds git.CredsStore
+ submoduleEnabled bool
+ getRepository func(ctx context.Context, url, project string) (*v1alpha1.Repository, error)
+ repoServerClientFuncs []func(*repo_mocks.RepoServerServiceClient)
}
type args struct {
ctx context.Context
@@ -38,49 +38,58 @@ func TestGetDirectories(t *testing.T) {
wantErr assert.ErrorAssertionFunc
}{
{name: "ErrorGettingRepos", fields: fields{
- getRepository: func(_ context.Context, _, _ string) (*v1alpha1.Repository, error) {
- return nil, errors.New("unable to get repos")
+ getRepository: func(ctx context.Context, url, project string) (*v1alpha1.Repository, error) {
+ return nil, fmt.Errorf("unable to get repos")
},
}, args: args{}, want: nil, wantErr: assert.Error},
{name: "ErrorGettingDirs", fields: fields{
- getRepository: func(_ context.Context, _, _ string) (*v1alpha1.Repository, error) {
+ getRepository: func(ctx context.Context, url, project string) (*v1alpha1.Repository, error) {
return &v1alpha1.Repository{}, nil
},
- getGitDirectories: func(_ context.Context, _ *apiclient.GitDirectoriesRequest) (*apiclient.GitDirectoriesResponse, error) {
- return nil, errors.New("unable to get dirs")
+ repoServerClientFuncs: []func(*repo_mocks.RepoServerServiceClient){
+ func(client *repo_mocks.RepoServerServiceClient) {
+ client.On("GetGitDirectories", mock.Anything, mock.Anything).Return(nil, fmt.Errorf("unable to get dirs"))
+ },
},
}, args: args{}, want: nil, wantErr: assert.Error},
{name: "HappyCase", fields: fields{
- getRepository: func(_ context.Context, _, _ string) (*v1alpha1.Repository, error) {
- return &v1alpha1.Repository{
- Repo: "foo",
- }, nil
- },
- getGitDirectories: func(_ context.Context, _ *apiclient.GitDirectoriesRequest) (*apiclient.GitDirectoriesResponse, error) {
- return &apiclient.GitDirectoriesResponse{
- Paths: []string{"foo", "foo/bar", "bar/foo"},
- }, nil
- },
- }, args: args{
- repoURL: "foo",
- }, want: []string{"foo", "foo/bar", "bar/foo"}, wantErr: assert.NoError},
- {name: "ErrorVerifyingCommit", fields: fields{
- getRepository: func(_ context.Context, _, _ string) (*v1alpha1.Repository, error) {
+ getRepository: func(ctx context.Context, url, project string) (*v1alpha1.Repository, error) {
return &v1alpha1.Repository{}, nil
},
- getGitDirectories: func(_ context.Context, _ *apiclient.GitDirectoriesRequest) (*apiclient.GitDirectoriesResponse, error) {
- return nil, errors.New("revision HEAD is not signed")
+ repoServerClientFuncs: []func(*repo_mocks.RepoServerServiceClient){
+ func(client *repo_mocks.RepoServerServiceClient) {
+ client.On("GetGitDirectories", mock.Anything, mock.Anything).Return(&apiclient.GitDirectoriesResponse{
+ Paths: []string{"foo", "foo/bar", "bar/foo"},
+ }, nil)
+ },
+ },
+ }, 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) {
+ return &v1alpha1.Repository{}, nil
+ },
+ repoServerClientFuncs: []func(*repo_mocks.RepoServerServiceClient){
+ func(client *repo_mocks.RepoServerServiceClient) {
+ client.On("GetGitDirectories", mock.Anything, mock.Anything).Return(nil, fmt.Errorf("revision HEAD is not signed"))
+ },
},
}, args: args{}, want: nil, wantErr: assert.Error},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- a := &argoCDService{
- getRepository: tt.fields.getRepository,
- submoduleEnabled: tt.fields.submoduleEnabled,
- getGitDirectoriesFromRepoServer: tt.fields.getGitDirectories,
+ mockRepoClient := &repo_mocks.RepoServerServiceClient{}
+ // decorate the mocks
+ for i := range tt.fields.repoServerClientFuncs {
+ tt.fields.repoServerClientFuncs[i](mockRepoClient)
}
- got, err := a.GetDirectories(tt.args.ctx, tt.args.repoURL, tt.args.revision, "", tt.args.noRevisionCache, tt.args.verifyCommit)
+
+ a := &argoCDService{
+ getRepository: tt.fields.getRepository,
+ storecreds: tt.fields.storecreds,
+ submoduleEnabled: tt.fields.submoduleEnabled,
+ repoServerClientSet: &repo_mocks.Clientset{RepoServerServiceClient: mockRepoClient},
+ }
+ got, err := a.GetDirectories(tt.args.ctx, tt.args.repoURL, tt.args.revision, tt.args.noRevisionCache, tt.args.verifyCommit)
if !tt.wantErr(t, err, fmt.Sprintf("GetDirectories(%v, %v, %v, %v)", tt.args.ctx, tt.args.repoURL, tt.args.revision, tt.args.noRevisionCache)) {
return
}
@@ -91,9 +100,10 @@ func TestGetDirectories(t *testing.T) {
func TestGetFiles(t *testing.T) {
type fields struct {
- submoduleEnabled bool
- getRepository func(ctx context.Context, url, project string) (*v1alpha1.Repository, error)
- getGitFiles func(ctx context.Context, req *apiclient.GitFilesRequest) (*apiclient.GitFilesResponse, error)
+ storecreds git.CredsStore
+ submoduleEnabled bool
+ repoServerClientFuncs []func(*repo_mocks.RepoServerServiceClient)
+ getRepository func(ctx context.Context, url, project string) (*v1alpha1.Repository, error)
}
type args struct {
ctx context.Context
@@ -111,55 +121,64 @@ func TestGetFiles(t *testing.T) {
wantErr assert.ErrorAssertionFunc
}{
{name: "ErrorGettingRepos", fields: fields{
- getRepository: func(_ context.Context, _, _ string) (*v1alpha1.Repository, error) {
- return nil, errors.New("unable to get repos")
+ getRepository: func(ctx context.Context, url, project string) (*v1alpha1.Repository, error) {
+ return nil, fmt.Errorf("unable to get repos")
},
}, args: args{}, want: nil, wantErr: assert.Error},
{name: "ErrorGettingFiles", fields: fields{
- getRepository: func(_ context.Context, _, _ string) (*v1alpha1.Repository, error) {
+ getRepository: func(ctx context.Context, url, project string) (*v1alpha1.Repository, error) {
return &v1alpha1.Repository{}, nil
},
- getGitFiles: func(_ context.Context, _ *apiclient.GitFilesRequest) (*apiclient.GitFilesResponse, error) {
- return nil, errors.New("unable to get files")
+ repoServerClientFuncs: []func(*repo_mocks.RepoServerServiceClient){
+ func(client *repo_mocks.RepoServerServiceClient) {
+ client.On("GetGitFiles", mock.Anything, mock.Anything).Return(nil, fmt.Errorf("unable to get files"))
+ },
},
}, args: args{}, want: nil, wantErr: assert.Error},
{name: "HappyCase", fields: fields{
- getRepository: func(_ context.Context, _, _ string) (*v1alpha1.Repository, error) {
- return &v1alpha1.Repository{
- Repo: "foo",
- }, nil
+ getRepository: func(ctx context.Context, url, project string) (*v1alpha1.Repository, error) {
+ return &v1alpha1.Repository{}, nil
},
- getGitFiles: func(_ context.Context, _ *apiclient.GitFilesRequest) (*apiclient.GitFilesResponse, error) {
- return &apiclient.GitFilesResponse{
- Map: map[string][]byte{
- "foo.json": []byte("hello: world!"),
- "bar.yaml": []byte("yay: appsets"),
- },
- }, nil
+ repoServerClientFuncs: []func(*repo_mocks.RepoServerServiceClient){
+ func(client *repo_mocks.RepoServerServiceClient) {
+ client.On("GetGitFiles", mock.Anything, mock.Anything).Return(&apiclient.GitFilesResponse{
+ Map: map[string][]byte{
+ "foo.json": []byte("hello: world!"),
+ "bar.yaml": []byte("yay: appsets"),
+ },
+ }, nil)
+ },
},
- }, args: args{
- repoURL: "foo",
- }, want: map[string][]byte{
+ }, args: args{}, want: map[string][]byte{
"foo.json": []byte("hello: world!"),
"bar.yaml": []byte("yay: appsets"),
}, wantErr: assert.NoError},
{name: "ErrorVerifyingCommit", fields: fields{
- getRepository: func(_ context.Context, _, _ string) (*v1alpha1.Repository, error) {
+ getRepository: func(ctx context.Context, url, project string) (*v1alpha1.Repository, error) {
return &v1alpha1.Repository{}, nil
},
- getGitFiles: func(_ context.Context, _ *apiclient.GitFilesRequest) (*apiclient.GitFilesResponse, error) {
- return nil, errors.New("revision HEAD is not signed")
+ repoServerClientFuncs: []func(*repo_mocks.RepoServerServiceClient){
+ func(client *repo_mocks.RepoServerServiceClient) {
+ client.On("GetGitFiles", mock.Anything, mock.Anything).Return(nil, fmt.Errorf("revision HEAD is not signed"))
+ },
},
}, args: args{}, want: nil, wantErr: assert.Error},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- a := &argoCDService{
- getRepository: tt.fields.getRepository,
- submoduleEnabled: tt.fields.submoduleEnabled,
- getGitFilesFromRepoServer: tt.fields.getGitFiles,
+ mockRepoClient := &repo_mocks.RepoServerServiceClient{}
+ // decorate the mocks
+ for i := range tt.fields.repoServerClientFuncs {
+ tt.fields.repoServerClientFuncs[i](mockRepoClient)
}
- got, err := a.GetFiles(tt.args.ctx, tt.args.repoURL, tt.args.revision, tt.args.pattern, "", tt.args.noRevisionCache, tt.args.verifyCommit)
+
+ a := &argoCDService{
+ getRepository: tt.fields.getRepository,
+ storecreds: tt.fields.storecreds,
+ submoduleEnabled: tt.fields.submoduleEnabled,
+ repoServerClientSet: &repo_mocks.Clientset{RepoServerServiceClient: mockRepoClient},
+ }
+ got, err := a.GetFiles(tt.args.ctx, tt.args.repoURL, tt.args.revision, tt.args.pattern, tt.args.noRevisionCache, tt.args.verifyCommit)
if !tt.wantErr(t, err, fmt.Sprintf("GetFiles(%v, %v, %v, %v, %v)", tt.args.ctx, tt.args.repoURL, tt.args.revision, tt.args.pattern, tt.args.noRevisionCache)) {
return
}
@@ -169,9 +188,9 @@ func TestGetFiles(t *testing.T) {
}
func TestNewArgoCDService(t *testing.T) {
- testNamespace := "test"
- clientset := fake.NewClientset()
- testDB := db.NewDB(testNamespace, settings.NewSettingsManager(t.Context(), clientset, testNamespace), clientset)
- service := NewArgoCDService(testDB, false, &repo_mocks.Clientset{}, false)
+ service, err := NewArgoCDService(func(ctx context.Context, url, project string) (*v1alpha1.Repository, error) {
+ return &v1alpha1.Repository{}, nil
+ }, false, &repo_mocks.Clientset{}, false)
+ require.NoError(t, err)
assert.NotNil(t, service)
}
diff --git a/applicationset/services/scm_provider/aws_codecommit.go b/applicationset/services/scm_provider/aws_codecommit.go
index 481645454a..7732ff5361 100644
--- a/applicationset/services/scm_provider/aws_codecommit.go
+++ b/applicationset/services/scm_provider/aws_codecommit.go
@@ -21,13 +21,13 @@ import (
"golang.org/x/exp/maps"
"k8s.io/utils/strings/slices"
- application "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ application "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
)
const (
resourceTypeCodeCommitRepository = "codecommit:repository"
- prefixGitURLHTTPS = "https://git-codecommit."
- prefixGitURLHTTPSFIPS = "https://git-codecommit-fips."
+ prefixGitUrlHttps = "https://git-codecommit."
+ prefixGitUrlHttpsFIPS = "https://git-codecommit-fips."
)
// AWSCodeCommitClient is a lean facade to the codecommitiface.CodeCommitAPI
@@ -315,16 +315,16 @@ func getCodeCommitRepoName(repoArn string) (string, error) {
// getCodeCommitFIPSEndpoint transforms provided https:// codecommit URL to a FIPS-compliant endpoint.
// note that the specified region must support FIPS, otherwise the returned URL won't be reachable
// see: https://docs.aws.amazon.com/codecommit/latest/userguide/regions.html#regions-git
-func getCodeCommitFIPSEndpoint(repoURL string) (string, error) {
- if strings.HasPrefix(repoURL, prefixGitURLHTTPSFIPS) {
- log.Debugf("provided repoUrl %s is already a fips endpoint", repoURL)
- return repoURL, nil
+func getCodeCommitFIPSEndpoint(repoUrl string) (string, error) {
+ if strings.HasPrefix(repoUrl, prefixGitUrlHttpsFIPS) {
+ log.Debugf("provided repoUrl %s is already a fips endpoint", repoUrl)
+ return repoUrl, nil
}
- if !strings.HasPrefix(repoURL, prefixGitURLHTTPS) {
- return "", fmt.Errorf("the provided https endpoint isn't recognized, cannot be transformed to FIPS endpoint: %s", repoURL)
+ if !strings.HasPrefix(repoUrl, prefixGitUrlHttps) {
+ return "", fmt.Errorf("the provided https endpoint isn't recognized, cannot be transformed to FIPS endpoint: %s", repoUrl)
}
// we already have the prefix, so we guarantee to replace exactly the prefix only.
- return strings.Replace(repoURL, prefixGitURLHTTPS, prefixGitURLHTTPSFIPS, 1), nil
+ return strings.Replace(repoUrl, prefixGitUrlHttps, prefixGitUrlHttpsFIPS, 1), nil
}
func hasAwsError(err error, codes ...string) bool {
diff --git a/applicationset/services/scm_provider/aws_codecommit/mocks/AWSCodeCommitClient.go b/applicationset/services/scm_provider/aws_codecommit/mocks/AWSCodeCommitClient.go
index a410802bc2..822ca9b275 100644
--- a/applicationset/services/scm_provider/aws_codecommit/mocks/AWSCodeCommitClient.go
+++ b/applicationset/services/scm_provider/aws_codecommit/mocks/AWSCodeCommitClient.go
@@ -1,16 +1,170 @@
-// Code generated by mockery; DO NOT EDIT.
-// github.com/vektra/mockery
-// template: testify
+// Code generated by mockery v2.53.4. DO NOT EDIT.
package mocks
import (
- "github.com/aws/aws-sdk-go/aws"
- "github.com/aws/aws-sdk-go/aws/request"
- "github.com/aws/aws-sdk-go/service/codecommit"
+ context "context"
+
+ codecommit "github.com/aws/aws-sdk-go/service/codecommit"
+
mock "github.com/stretchr/testify/mock"
+
+ request "github.com/aws/aws-sdk-go/aws/request"
)
+// AWSCodeCommitClient is an autogenerated mock type for the AWSCodeCommitClient type
+type AWSCodeCommitClient struct {
+ mock.Mock
+}
+
+// GetFolderWithContext provides a mock function with given fields: _a0, _a1, _a2
+func (_m *AWSCodeCommitClient) GetFolderWithContext(_a0 context.Context, _a1 *codecommit.GetFolderInput, _a2 ...request.Option) (*codecommit.GetFolderOutput, error) {
+ _va := make([]interface{}, len(_a2))
+ for _i := range _a2 {
+ _va[_i] = _a2[_i]
+ }
+ var _ca []interface{}
+ _ca = append(_ca, _a0, _a1)
+ _ca = append(_ca, _va...)
+ ret := _m.Called(_ca...)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetFolderWithContext")
+ }
+
+ var r0 *codecommit.GetFolderOutput
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, *codecommit.GetFolderInput, ...request.Option) (*codecommit.GetFolderOutput, error)); ok {
+ return rf(_a0, _a1, _a2...)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, *codecommit.GetFolderInput, ...request.Option) *codecommit.GetFolderOutput); ok {
+ r0 = rf(_a0, _a1, _a2...)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*codecommit.GetFolderOutput)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, *codecommit.GetFolderInput, ...request.Option) error); ok {
+ r1 = rf(_a0, _a1, _a2...)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetRepositoryWithContext provides a mock function with given fields: _a0, _a1, _a2
+func (_m *AWSCodeCommitClient) GetRepositoryWithContext(_a0 context.Context, _a1 *codecommit.GetRepositoryInput, _a2 ...request.Option) (*codecommit.GetRepositoryOutput, error) {
+ _va := make([]interface{}, len(_a2))
+ for _i := range _a2 {
+ _va[_i] = _a2[_i]
+ }
+ var _ca []interface{}
+ _ca = append(_ca, _a0, _a1)
+ _ca = append(_ca, _va...)
+ ret := _m.Called(_ca...)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetRepositoryWithContext")
+ }
+
+ var r0 *codecommit.GetRepositoryOutput
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, *codecommit.GetRepositoryInput, ...request.Option) (*codecommit.GetRepositoryOutput, error)); ok {
+ return rf(_a0, _a1, _a2...)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, *codecommit.GetRepositoryInput, ...request.Option) *codecommit.GetRepositoryOutput); ok {
+ r0 = rf(_a0, _a1, _a2...)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*codecommit.GetRepositoryOutput)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, *codecommit.GetRepositoryInput, ...request.Option) error); ok {
+ r1 = rf(_a0, _a1, _a2...)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// ListBranchesWithContext provides a mock function with given fields: _a0, _a1, _a2
+func (_m *AWSCodeCommitClient) ListBranchesWithContext(_a0 context.Context, _a1 *codecommit.ListBranchesInput, _a2 ...request.Option) (*codecommit.ListBranchesOutput, error) {
+ _va := make([]interface{}, len(_a2))
+ for _i := range _a2 {
+ _va[_i] = _a2[_i]
+ }
+ var _ca []interface{}
+ _ca = append(_ca, _a0, _a1)
+ _ca = append(_ca, _va...)
+ ret := _m.Called(_ca...)
+
+ if len(ret) == 0 {
+ panic("no return value specified for ListBranchesWithContext")
+ }
+
+ var r0 *codecommit.ListBranchesOutput
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, *codecommit.ListBranchesInput, ...request.Option) (*codecommit.ListBranchesOutput, error)); ok {
+ return rf(_a0, _a1, _a2...)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, *codecommit.ListBranchesInput, ...request.Option) *codecommit.ListBranchesOutput); ok {
+ r0 = rf(_a0, _a1, _a2...)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*codecommit.ListBranchesOutput)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, *codecommit.ListBranchesInput, ...request.Option) error); ok {
+ r1 = rf(_a0, _a1, _a2...)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// ListRepositoriesWithContext provides a mock function with given fields: _a0, _a1, _a2
+func (_m *AWSCodeCommitClient) ListRepositoriesWithContext(_a0 context.Context, _a1 *codecommit.ListRepositoriesInput, _a2 ...request.Option) (*codecommit.ListRepositoriesOutput, error) {
+ _va := make([]interface{}, len(_a2))
+ for _i := range _a2 {
+ _va[_i] = _a2[_i]
+ }
+ var _ca []interface{}
+ _ca = append(_ca, _a0, _a1)
+ _ca = append(_ca, _va...)
+ ret := _m.Called(_ca...)
+
+ if len(ret) == 0 {
+ panic("no return value specified for ListRepositoriesWithContext")
+ }
+
+ var r0 *codecommit.ListRepositoriesOutput
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, *codecommit.ListRepositoriesInput, ...request.Option) (*codecommit.ListRepositoriesOutput, error)); ok {
+ return rf(_a0, _a1, _a2...)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, *codecommit.ListRepositoriesInput, ...request.Option) *codecommit.ListRepositoriesOutput); ok {
+ r0 = rf(_a0, _a1, _a2...)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*codecommit.ListRepositoriesOutput)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, *codecommit.ListRepositoriesInput, ...request.Option) error); ok {
+ r1 = rf(_a0, _a1, _a2...)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
// NewAWSCodeCommitClient creates a new instance of AWSCodeCommitClient. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
// The first argument is typically a *testing.T value.
func NewAWSCodeCommitClient(t interface {
@@ -24,308 +178,3 @@ func NewAWSCodeCommitClient(t interface {
return mock
}
-
-// AWSCodeCommitClient is an autogenerated mock type for the AWSCodeCommitClient type
-type AWSCodeCommitClient struct {
- mock.Mock
-}
-
-type AWSCodeCommitClient_Expecter struct {
- mock *mock.Mock
-}
-
-func (_m *AWSCodeCommitClient) EXPECT() *AWSCodeCommitClient_Expecter {
- return &AWSCodeCommitClient_Expecter{mock: &_m.Mock}
-}
-
-// GetFolderWithContext provides a mock function for the type AWSCodeCommitClient
-func (_mock *AWSCodeCommitClient) GetFolderWithContext(v aws.Context, getFolderInput *codecommit.GetFolderInput, options ...request.Option) (*codecommit.GetFolderOutput, error) {
- // request.Option
- _va := make([]interface{}, len(options))
- for _i := range options {
- _va[_i] = options[_i]
- }
- var _ca []interface{}
- _ca = append(_ca, v, getFolderInput)
- _ca = append(_ca, _va...)
- ret := _mock.Called(_ca...)
-
- if len(ret) == 0 {
- panic("no return value specified for GetFolderWithContext")
- }
-
- var r0 *codecommit.GetFolderOutput
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(aws.Context, *codecommit.GetFolderInput, ...request.Option) (*codecommit.GetFolderOutput, error)); ok {
- return returnFunc(v, getFolderInput, options...)
- }
- if returnFunc, ok := ret.Get(0).(func(aws.Context, *codecommit.GetFolderInput, ...request.Option) *codecommit.GetFolderOutput); ok {
- r0 = returnFunc(v, getFolderInput, options...)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*codecommit.GetFolderOutput)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(aws.Context, *codecommit.GetFolderInput, ...request.Option) error); ok {
- r1 = returnFunc(v, getFolderInput, options...)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// AWSCodeCommitClient_GetFolderWithContext_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetFolderWithContext'
-type AWSCodeCommitClient_GetFolderWithContext_Call struct {
- *mock.Call
-}
-
-// GetFolderWithContext is a helper method to define mock.On call
-// - v
-// - getFolderInput
-// - options
-func (_e *AWSCodeCommitClient_Expecter) GetFolderWithContext(v interface{}, getFolderInput interface{}, options ...interface{}) *AWSCodeCommitClient_GetFolderWithContext_Call {
- return &AWSCodeCommitClient_GetFolderWithContext_Call{Call: _e.mock.On("GetFolderWithContext",
- append([]interface{}{v, getFolderInput}, options...)...)}
-}
-
-func (_c *AWSCodeCommitClient_GetFolderWithContext_Call) Run(run func(v aws.Context, getFolderInput *codecommit.GetFolderInput, options ...request.Option)) *AWSCodeCommitClient_GetFolderWithContext_Call {
- _c.Call.Run(func(args mock.Arguments) {
- variadicArgs := make([]request.Option, len(args)-2)
- for i, a := range args[2:] {
- if a != nil {
- variadicArgs[i] = a.(request.Option)
- }
- }
- run(args[0].(aws.Context), args[1].(*codecommit.GetFolderInput), variadicArgs...)
- })
- return _c
-}
-
-func (_c *AWSCodeCommitClient_GetFolderWithContext_Call) Return(getFolderOutput *codecommit.GetFolderOutput, err error) *AWSCodeCommitClient_GetFolderWithContext_Call {
- _c.Call.Return(getFolderOutput, err)
- return _c
-}
-
-func (_c *AWSCodeCommitClient_GetFolderWithContext_Call) RunAndReturn(run func(v aws.Context, getFolderInput *codecommit.GetFolderInput, options ...request.Option) (*codecommit.GetFolderOutput, error)) *AWSCodeCommitClient_GetFolderWithContext_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetRepositoryWithContext provides a mock function for the type AWSCodeCommitClient
-func (_mock *AWSCodeCommitClient) GetRepositoryWithContext(v aws.Context, getRepositoryInput *codecommit.GetRepositoryInput, options ...request.Option) (*codecommit.GetRepositoryOutput, error) {
- // request.Option
- _va := make([]interface{}, len(options))
- for _i := range options {
- _va[_i] = options[_i]
- }
- var _ca []interface{}
- _ca = append(_ca, v, getRepositoryInput)
- _ca = append(_ca, _va...)
- ret := _mock.Called(_ca...)
-
- if len(ret) == 0 {
- panic("no return value specified for GetRepositoryWithContext")
- }
-
- var r0 *codecommit.GetRepositoryOutput
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(aws.Context, *codecommit.GetRepositoryInput, ...request.Option) (*codecommit.GetRepositoryOutput, error)); ok {
- return returnFunc(v, getRepositoryInput, options...)
- }
- if returnFunc, ok := ret.Get(0).(func(aws.Context, *codecommit.GetRepositoryInput, ...request.Option) *codecommit.GetRepositoryOutput); ok {
- r0 = returnFunc(v, getRepositoryInput, options...)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*codecommit.GetRepositoryOutput)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(aws.Context, *codecommit.GetRepositoryInput, ...request.Option) error); ok {
- r1 = returnFunc(v, getRepositoryInput, options...)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// AWSCodeCommitClient_GetRepositoryWithContext_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetRepositoryWithContext'
-type AWSCodeCommitClient_GetRepositoryWithContext_Call struct {
- *mock.Call
-}
-
-// GetRepositoryWithContext is a helper method to define mock.On call
-// - v
-// - getRepositoryInput
-// - options
-func (_e *AWSCodeCommitClient_Expecter) GetRepositoryWithContext(v interface{}, getRepositoryInput interface{}, options ...interface{}) *AWSCodeCommitClient_GetRepositoryWithContext_Call {
- return &AWSCodeCommitClient_GetRepositoryWithContext_Call{Call: _e.mock.On("GetRepositoryWithContext",
- append([]interface{}{v, getRepositoryInput}, options...)...)}
-}
-
-func (_c *AWSCodeCommitClient_GetRepositoryWithContext_Call) Run(run func(v aws.Context, getRepositoryInput *codecommit.GetRepositoryInput, options ...request.Option)) *AWSCodeCommitClient_GetRepositoryWithContext_Call {
- _c.Call.Run(func(args mock.Arguments) {
- variadicArgs := make([]request.Option, len(args)-2)
- for i, a := range args[2:] {
- if a != nil {
- variadicArgs[i] = a.(request.Option)
- }
- }
- run(args[0].(aws.Context), args[1].(*codecommit.GetRepositoryInput), variadicArgs...)
- })
- return _c
-}
-
-func (_c *AWSCodeCommitClient_GetRepositoryWithContext_Call) Return(getRepositoryOutput *codecommit.GetRepositoryOutput, err error) *AWSCodeCommitClient_GetRepositoryWithContext_Call {
- _c.Call.Return(getRepositoryOutput, err)
- return _c
-}
-
-func (_c *AWSCodeCommitClient_GetRepositoryWithContext_Call) RunAndReturn(run func(v aws.Context, getRepositoryInput *codecommit.GetRepositoryInput, options ...request.Option) (*codecommit.GetRepositoryOutput, error)) *AWSCodeCommitClient_GetRepositoryWithContext_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// ListBranchesWithContext provides a mock function for the type AWSCodeCommitClient
-func (_mock *AWSCodeCommitClient) ListBranchesWithContext(v aws.Context, listBranchesInput *codecommit.ListBranchesInput, options ...request.Option) (*codecommit.ListBranchesOutput, error) {
- // request.Option
- _va := make([]interface{}, len(options))
- for _i := range options {
- _va[_i] = options[_i]
- }
- var _ca []interface{}
- _ca = append(_ca, v, listBranchesInput)
- _ca = append(_ca, _va...)
- ret := _mock.Called(_ca...)
-
- if len(ret) == 0 {
- panic("no return value specified for ListBranchesWithContext")
- }
-
- var r0 *codecommit.ListBranchesOutput
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(aws.Context, *codecommit.ListBranchesInput, ...request.Option) (*codecommit.ListBranchesOutput, error)); ok {
- return returnFunc(v, listBranchesInput, options...)
- }
- if returnFunc, ok := ret.Get(0).(func(aws.Context, *codecommit.ListBranchesInput, ...request.Option) *codecommit.ListBranchesOutput); ok {
- r0 = returnFunc(v, listBranchesInput, options...)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*codecommit.ListBranchesOutput)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(aws.Context, *codecommit.ListBranchesInput, ...request.Option) error); ok {
- r1 = returnFunc(v, listBranchesInput, options...)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// AWSCodeCommitClient_ListBranchesWithContext_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListBranchesWithContext'
-type AWSCodeCommitClient_ListBranchesWithContext_Call struct {
- *mock.Call
-}
-
-// ListBranchesWithContext is a helper method to define mock.On call
-// - v
-// - listBranchesInput
-// - options
-func (_e *AWSCodeCommitClient_Expecter) ListBranchesWithContext(v interface{}, listBranchesInput interface{}, options ...interface{}) *AWSCodeCommitClient_ListBranchesWithContext_Call {
- return &AWSCodeCommitClient_ListBranchesWithContext_Call{Call: _e.mock.On("ListBranchesWithContext",
- append([]interface{}{v, listBranchesInput}, options...)...)}
-}
-
-func (_c *AWSCodeCommitClient_ListBranchesWithContext_Call) Run(run func(v aws.Context, listBranchesInput *codecommit.ListBranchesInput, options ...request.Option)) *AWSCodeCommitClient_ListBranchesWithContext_Call {
- _c.Call.Run(func(args mock.Arguments) {
- variadicArgs := make([]request.Option, len(args)-2)
- for i, a := range args[2:] {
- if a != nil {
- variadicArgs[i] = a.(request.Option)
- }
- }
- run(args[0].(aws.Context), args[1].(*codecommit.ListBranchesInput), variadicArgs...)
- })
- return _c
-}
-
-func (_c *AWSCodeCommitClient_ListBranchesWithContext_Call) Return(listBranchesOutput *codecommit.ListBranchesOutput, err error) *AWSCodeCommitClient_ListBranchesWithContext_Call {
- _c.Call.Return(listBranchesOutput, err)
- return _c
-}
-
-func (_c *AWSCodeCommitClient_ListBranchesWithContext_Call) RunAndReturn(run func(v aws.Context, listBranchesInput *codecommit.ListBranchesInput, options ...request.Option) (*codecommit.ListBranchesOutput, error)) *AWSCodeCommitClient_ListBranchesWithContext_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// ListRepositoriesWithContext provides a mock function for the type AWSCodeCommitClient
-func (_mock *AWSCodeCommitClient) ListRepositoriesWithContext(v aws.Context, listRepositoriesInput *codecommit.ListRepositoriesInput, options ...request.Option) (*codecommit.ListRepositoriesOutput, error) {
- // request.Option
- _va := make([]interface{}, len(options))
- for _i := range options {
- _va[_i] = options[_i]
- }
- var _ca []interface{}
- _ca = append(_ca, v, listRepositoriesInput)
- _ca = append(_ca, _va...)
- ret := _mock.Called(_ca...)
-
- if len(ret) == 0 {
- panic("no return value specified for ListRepositoriesWithContext")
- }
-
- var r0 *codecommit.ListRepositoriesOutput
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(aws.Context, *codecommit.ListRepositoriesInput, ...request.Option) (*codecommit.ListRepositoriesOutput, error)); ok {
- return returnFunc(v, listRepositoriesInput, options...)
- }
- if returnFunc, ok := ret.Get(0).(func(aws.Context, *codecommit.ListRepositoriesInput, ...request.Option) *codecommit.ListRepositoriesOutput); ok {
- r0 = returnFunc(v, listRepositoriesInput, options...)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*codecommit.ListRepositoriesOutput)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(aws.Context, *codecommit.ListRepositoriesInput, ...request.Option) error); ok {
- r1 = returnFunc(v, listRepositoriesInput, options...)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// AWSCodeCommitClient_ListRepositoriesWithContext_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListRepositoriesWithContext'
-type AWSCodeCommitClient_ListRepositoriesWithContext_Call struct {
- *mock.Call
-}
-
-// ListRepositoriesWithContext is a helper method to define mock.On call
-// - v
-// - listRepositoriesInput
-// - options
-func (_e *AWSCodeCommitClient_Expecter) ListRepositoriesWithContext(v interface{}, listRepositoriesInput interface{}, options ...interface{}) *AWSCodeCommitClient_ListRepositoriesWithContext_Call {
- return &AWSCodeCommitClient_ListRepositoriesWithContext_Call{Call: _e.mock.On("ListRepositoriesWithContext",
- append([]interface{}{v, listRepositoriesInput}, options...)...)}
-}
-
-func (_c *AWSCodeCommitClient_ListRepositoriesWithContext_Call) Run(run func(v aws.Context, listRepositoriesInput *codecommit.ListRepositoriesInput, options ...request.Option)) *AWSCodeCommitClient_ListRepositoriesWithContext_Call {
- _c.Call.Run(func(args mock.Arguments) {
- variadicArgs := make([]request.Option, len(args)-2)
- for i, a := range args[2:] {
- if a != nil {
- variadicArgs[i] = a.(request.Option)
- }
- }
- run(args[0].(aws.Context), args[1].(*codecommit.ListRepositoriesInput), variadicArgs...)
- })
- return _c
-}
-
-func (_c *AWSCodeCommitClient_ListRepositoriesWithContext_Call) Return(listRepositoriesOutput *codecommit.ListRepositoriesOutput, err error) *AWSCodeCommitClient_ListRepositoriesWithContext_Call {
- _c.Call.Return(listRepositoriesOutput, err)
- return _c
-}
-
-func (_c *AWSCodeCommitClient_ListRepositoriesWithContext_Call) RunAndReturn(run func(v aws.Context, listRepositoriesInput *codecommit.ListRepositoriesInput, options ...request.Option) (*codecommit.ListRepositoriesOutput, error)) *AWSCodeCommitClient_ListRepositoriesWithContext_Call {
- _c.Call.Return(run)
- return _c
-}
diff --git a/applicationset/services/scm_provider/aws_codecommit/mocks/AWSTaggingClient.go b/applicationset/services/scm_provider/aws_codecommit/mocks/AWSTaggingClient.go
index 5e9cbc714f..e454e2a9d9 100644
--- a/applicationset/services/scm_provider/aws_codecommit/mocks/AWSTaggingClient.go
+++ b/applicationset/services/scm_provider/aws_codecommit/mocks/AWSTaggingClient.go
@@ -1,16 +1,58 @@
-// Code generated by mockery; DO NOT EDIT.
-// github.com/vektra/mockery
-// template: testify
+// Code generated by mockery v2.53.4. DO NOT EDIT.
package mocks
import (
- "github.com/aws/aws-sdk-go/aws"
- "github.com/aws/aws-sdk-go/aws/request"
- "github.com/aws/aws-sdk-go/service/resourcegroupstaggingapi"
+ context "context"
+
+ request "github.com/aws/aws-sdk-go/aws/request"
mock "github.com/stretchr/testify/mock"
+
+ resourcegroupstaggingapi "github.com/aws/aws-sdk-go/service/resourcegroupstaggingapi"
)
+// AWSTaggingClient is an autogenerated mock type for the AWSTaggingClient type
+type AWSTaggingClient struct {
+ mock.Mock
+}
+
+// GetResourcesWithContext provides a mock function with given fields: _a0, _a1, _a2
+func (_m *AWSTaggingClient) GetResourcesWithContext(_a0 context.Context, _a1 *resourcegroupstaggingapi.GetResourcesInput, _a2 ...request.Option) (*resourcegroupstaggingapi.GetResourcesOutput, error) {
+ _va := make([]interface{}, len(_a2))
+ for _i := range _a2 {
+ _va[_i] = _a2[_i]
+ }
+ var _ca []interface{}
+ _ca = append(_ca, _a0, _a1)
+ _ca = append(_ca, _va...)
+ ret := _m.Called(_ca...)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetResourcesWithContext")
+ }
+
+ var r0 *resourcegroupstaggingapi.GetResourcesOutput
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, *resourcegroupstaggingapi.GetResourcesInput, ...request.Option) (*resourcegroupstaggingapi.GetResourcesOutput, error)); ok {
+ return rf(_a0, _a1, _a2...)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, *resourcegroupstaggingapi.GetResourcesInput, ...request.Option) *resourcegroupstaggingapi.GetResourcesOutput); ok {
+ r0 = rf(_a0, _a1, _a2...)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*resourcegroupstaggingapi.GetResourcesOutput)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, *resourcegroupstaggingapi.GetResourcesInput, ...request.Option) error); ok {
+ r1 = rf(_a0, _a1, _a2...)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
// NewAWSTaggingClient creates a new instance of AWSTaggingClient. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
// The first argument is typically a *testing.T value.
func NewAWSTaggingClient(t interface {
@@ -24,89 +66,3 @@ func NewAWSTaggingClient(t interface {
return mock
}
-
-// AWSTaggingClient is an autogenerated mock type for the AWSTaggingClient type
-type AWSTaggingClient struct {
- mock.Mock
-}
-
-type AWSTaggingClient_Expecter struct {
- mock *mock.Mock
-}
-
-func (_m *AWSTaggingClient) EXPECT() *AWSTaggingClient_Expecter {
- return &AWSTaggingClient_Expecter{mock: &_m.Mock}
-}
-
-// GetResourcesWithContext provides a mock function for the type AWSTaggingClient
-func (_mock *AWSTaggingClient) GetResourcesWithContext(v aws.Context, getResourcesInput *resourcegroupstaggingapi.GetResourcesInput, options ...request.Option) (*resourcegroupstaggingapi.GetResourcesOutput, error) {
- // request.Option
- _va := make([]interface{}, len(options))
- for _i := range options {
- _va[_i] = options[_i]
- }
- var _ca []interface{}
- _ca = append(_ca, v, getResourcesInput)
- _ca = append(_ca, _va...)
- ret := _mock.Called(_ca...)
-
- if len(ret) == 0 {
- panic("no return value specified for GetResourcesWithContext")
- }
-
- var r0 *resourcegroupstaggingapi.GetResourcesOutput
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(aws.Context, *resourcegroupstaggingapi.GetResourcesInput, ...request.Option) (*resourcegroupstaggingapi.GetResourcesOutput, error)); ok {
- return returnFunc(v, getResourcesInput, options...)
- }
- if returnFunc, ok := ret.Get(0).(func(aws.Context, *resourcegroupstaggingapi.GetResourcesInput, ...request.Option) *resourcegroupstaggingapi.GetResourcesOutput); ok {
- r0 = returnFunc(v, getResourcesInput, options...)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*resourcegroupstaggingapi.GetResourcesOutput)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(aws.Context, *resourcegroupstaggingapi.GetResourcesInput, ...request.Option) error); ok {
- r1 = returnFunc(v, getResourcesInput, options...)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// AWSTaggingClient_GetResourcesWithContext_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetResourcesWithContext'
-type AWSTaggingClient_GetResourcesWithContext_Call struct {
- *mock.Call
-}
-
-// GetResourcesWithContext is a helper method to define mock.On call
-// - v
-// - getResourcesInput
-// - options
-func (_e *AWSTaggingClient_Expecter) GetResourcesWithContext(v interface{}, getResourcesInput interface{}, options ...interface{}) *AWSTaggingClient_GetResourcesWithContext_Call {
- return &AWSTaggingClient_GetResourcesWithContext_Call{Call: _e.mock.On("GetResourcesWithContext",
- append([]interface{}{v, getResourcesInput}, options...)...)}
-}
-
-func (_c *AWSTaggingClient_GetResourcesWithContext_Call) Run(run func(v aws.Context, getResourcesInput *resourcegroupstaggingapi.GetResourcesInput, options ...request.Option)) *AWSTaggingClient_GetResourcesWithContext_Call {
- _c.Call.Run(func(args mock.Arguments) {
- variadicArgs := make([]request.Option, len(args)-2)
- for i, a := range args[2:] {
- if a != nil {
- variadicArgs[i] = a.(request.Option)
- }
- }
- run(args[0].(aws.Context), args[1].(*resourcegroupstaggingapi.GetResourcesInput), variadicArgs...)
- })
- return _c
-}
-
-func (_c *AWSTaggingClient_GetResourcesWithContext_Call) Return(getResourcesOutput *resourcegroupstaggingapi.GetResourcesOutput, err error) *AWSTaggingClient_GetResourcesWithContext_Call {
- _c.Call.Return(getResourcesOutput, err)
- return _c
-}
-
-func (_c *AWSTaggingClient_GetResourcesWithContext_Call) RunAndReturn(run func(v aws.Context, getResourcesInput *resourcegroupstaggingapi.GetResourcesInput, options ...request.Option) (*resourcegroupstaggingapi.GetResourcesOutput, error)) *AWSTaggingClient_GetResourcesWithContext_Call {
- _c.Call.Return(run)
- return _c
-}
diff --git a/applicationset/services/scm_provider/aws_codecommit_test.go b/applicationset/services/scm_provider/aws_codecommit_test.go
index fc5b7fa5d1..00d8240973 100644
--- a/applicationset/services/scm_provider/aws_codecommit_test.go
+++ b/applicationset/services/scm_provider/aws_codecommit_test.go
@@ -1,6 +1,7 @@
package scm_provider
import (
+ "context"
"errors"
"sort"
"testing"
@@ -12,8 +13,8 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
- "github.com/argoproj/argo-cd/v3/applicationset/services/scm_provider/aws_codecommit/mocks"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/applicationset/services/scm_provider/aws_codecommit/mocks"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
)
type awsCodeCommitTestRepository struct {
@@ -22,7 +23,7 @@ type awsCodeCommitTestRepository struct {
arn string
accountId string
defaultBranch string
- expectedCloneURL string
+ expectedCloneUrl string
getRepositoryError error
getRepositoryNilMetadata bool
valid bool
@@ -48,7 +49,7 @@ func TestAWSCodeCommitListRepos(t *testing.T) {
id: "8235624d-d248-4df9-a983-2558b01dbe83",
arn: "arn:aws:codecommit:us-east-1:111111111111:repo1",
defaultBranch: "main",
- expectedCloneURL: "https://git-codecommit.us-east-1.amazonaws.com/v1/repos/repo1",
+ expectedCloneUrl: "https://git-codecommit.us-east-1.amazonaws.com/v1/repos/repo1",
valid: true,
},
},
@@ -73,7 +74,7 @@ func TestAWSCodeCommitListRepos(t *testing.T) {
id: "8235624d-d248-4df9-a983-2558b01dbe83",
arn: "arn:aws:codecommit:us-east-1:111111111111:repo1",
defaultBranch: "main",
- expectedCloneURL: "https://git-codecommit-fips.us-east-1.amazonaws.com/v1/repos/repo1",
+ expectedCloneUrl: "https://git-codecommit-fips.us-east-1.amazonaws.com/v1/repos/repo1",
valid: true,
},
},
@@ -95,7 +96,7 @@ func TestAWSCodeCommitListRepos(t *testing.T) {
id: "8235624d-d248-4df9-a983-2558b01dbe83",
arn: "arn:aws:codecommit:us-east-1:111111111111:repo1",
defaultBranch: "main",
- expectedCloneURL: "ssh://git-codecommit.us-east-1.amazonaws.com/v1/repos/repo1",
+ expectedCloneUrl: "ssh://git-codecommit.us-east-1.amazonaws.com/v1/repos/repo1",
valid: true,
},
{
@@ -159,7 +160,7 @@ func TestAWSCodeCommitListRepos(t *testing.T) {
t.Run(testCase.name, func(t *testing.T) {
codeCommitClient := mocks.NewAWSCodeCommitClient(t)
taggingClient := mocks.NewAWSTaggingClient(t)
- ctx := t.Context()
+ ctx := context.Background()
codecommitRepoNameIdPairs := make([]*codecommit.RepositoryNameIdPair, 0)
resourceTaggings := make([]*resourcegroupstaggingapi.ResourceTagMapping, 0)
validRepositories := make([]*awsCodeCommitTestRepository, 0)
@@ -225,7 +226,7 @@ func TestAWSCodeCommitListRepos(t *testing.T) {
assert.Equal(t, originRepo.name, repo.Repository)
assert.Equal(t, originRepo.id, repo.RepositoryId)
assert.Equal(t, originRepo.defaultBranch, repo.Branch)
- assert.Equal(t, originRepo.expectedCloneURL, repo.URL)
+ assert.Equal(t, originRepo.expectedCloneUrl, repo.URL)
assert.Empty(t, repo.SHA, "SHA is always empty")
}
}
@@ -348,7 +349,7 @@ func TestAWSCodeCommitRepoHasPath(t *testing.T) {
t.Run(testCase.name, func(t *testing.T) {
codeCommitClient := mocks.NewAWSCodeCommitClient(t)
taggingClient := mocks.NewAWSTaggingClient(t)
- ctx := t.Context()
+ ctx := context.Background()
if testCase.expectedGetFolderPath != "" {
codeCommitClient.
On("GetFolderWithContext", ctx, &codecommit.GetFolderInput{
@@ -381,7 +382,7 @@ func TestAWSCodeCommitGetBranches(t *testing.T) {
id := "1a64adc4-2fb5-4abd-afe7-127984ba83c0"
defaultBranch := "main"
organization := "111111111111"
- cloneURL := "https://git-codecommit.us-east-1.amazonaws.com/v1/repos/repo1"
+ cloneUrl := "https://git-codecommit.us-east-1.amazonaws.com/v1/repos/repo1"
testCases := []struct {
name string
@@ -421,7 +422,7 @@ func TestAWSCodeCommitGetBranches(t *testing.T) {
t.Run(testCase.name, func(t *testing.T) {
codeCommitClient := mocks.NewAWSCodeCommitClient(t)
taggingClient := mocks.NewAWSTaggingClient(t)
- ctx := t.Context()
+ ctx := context.Background()
if testCase.allBranches {
codeCommitClient.
On("ListBranchesWithContext", ctx, &codecommit.ListBranchesInput{
@@ -444,7 +445,7 @@ func TestAWSCodeCommitGetBranches(t *testing.T) {
actual, err := provider.GetBranches(ctx, &Repository{
Organization: organization,
Repository: name,
- URL: cloneURL,
+ URL: cloneUrl,
RepositoryId: id,
})
if testCase.expectOverallError {
@@ -453,7 +454,7 @@ func TestAWSCodeCommitGetBranches(t *testing.T) {
assertCopiedProperties := func(repo *Repository) {
assert.Equal(t, id, repo.RepositoryId)
assert.Equal(t, name, repo.Repository)
- assert.Equal(t, cloneURL, repo.URL)
+ assert.Equal(t, cloneUrl, repo.URL)
assert.Equal(t, organization, repo.Organization)
assert.Empty(t, repo.SHA)
}
diff --git a/applicationset/services/scm_provider/azure_devops.go b/applicationset/services/scm_provider/azure_devops.go
index afda2551ec..a4bb50a023 100644
--- a/applicationset/services/scm_provider/azure_devops.go
+++ b/applicationset/services/scm_provider/azure_devops.go
@@ -8,8 +8,8 @@ import (
"strings"
"github.com/google/uuid"
- "github.com/microsoft/azure-devops-go-api/azuredevops/v7"
- azureGit "github.com/microsoft/azure-devops-go-api/azuredevops/v7/git"
+ "github.com/microsoft/azure-devops-go-api/azuredevops"
+ azureGit "github.com/microsoft/azure-devops-go-api/azuredevops/git"
)
const AZURE_DEVOPS_DEFAULT_URL = "https://dev.azure.com"
@@ -57,9 +57,9 @@ var (
_ AzureDevOpsClientFactory = &devopsFactoryImpl{}
)
-func NewAzureDevOpsProvider(accessToken string, org string, url string, project string, allBranches bool) (*AzureDevOpsProvider, error) {
+func NewAzureDevOpsProvider(ctx context.Context, accessToken string, org string, url string, project string, allBranches bool) (*AzureDevOpsProvider, error) {
if accessToken == "" {
- return nil, errors.New("no access token provided")
+ return nil, fmt.Errorf("no access token provided")
}
devOpsURL, err := getValidDevOpsURL(url, org)
@@ -72,7 +72,7 @@ func NewAzureDevOpsProvider(accessToken string, org string, url string, project
return &AzureDevOpsProvider{organization: org, teamProject: project, accessToken: accessToken, clientFactory: &devopsFactoryImpl{connection: connection}, allBranches: allBranches}, nil
}
-func (g *AzureDevOpsProvider) ListRepos(ctx context.Context, _ string) ([]*Repository, error) {
+func (g *AzureDevOpsProvider) ListRepos(ctx context.Context, cloneProtocol string) ([]*Repository, error) {
gitClient, err := g.clientFactory.GetClient(ctx)
if err != nil {
return nil, fmt.Errorf("failed to get Azure DevOps client: %w", err)
@@ -107,7 +107,7 @@ func (g *AzureDevOpsProvider) RepoHasPath(ctx context.Context, repo *Repository,
}
var repoId string
- if uuid, isUUID := repo.RepositoryId.(uuid.UUID); isUUID { // most likely an UUID, but do type-safe check anyway. Do %v fallback if not expected type.
+ if uuid, isUuid := repo.RepositoryId.(uuid.UUID); isUuid { // most likely an UUID, but do type-safe check anyway. Do %v fallback if not expected type.
repoId = uuid.String()
} else {
repoId = fmt.Sprintf("%v", repo.RepositoryId)
diff --git a/applicationset/services/scm_provider/azure_devops/git/mocks/Client.go b/applicationset/services/scm_provider/azure_devops/git/mocks/Client.go
index 9bec031656..4fd54456ca 100644
--- a/applicationset/services/scm_provider/azure_devops/git/mocks/Client.go
+++ b/applicationset/services/scm_provider/azure_devops/git/mocks/Client.go
@@ -1,19 +1,3325 @@
-// Code generated by mockery; DO NOT EDIT.
-// github.com/vektra/mockery
-// template: testify
+// Code generated by mockery v2.53.4. DO NOT EDIT.
package mocks
import (
- "context"
- "io"
+ context "context"
+
+ core "github.com/microsoft/azure-devops-go-api/azuredevops/core"
+ git "github.com/microsoft/azure-devops-go-api/azuredevops/git"
+
+ io "io"
- "github.com/microsoft/azure-devops-go-api/azuredevops/v7/core"
- "github.com/microsoft/azure-devops-go-api/azuredevops/v7/git"
- "github.com/microsoft/azure-devops-go-api/azuredevops/v7/webapi"
mock "github.com/stretchr/testify/mock"
+
+ webapi "github.com/microsoft/azure-devops-go-api/azuredevops/webapi"
)
+// Client is an autogenerated mock type for the Client type
+type Client struct {
+ mock.Mock
+}
+
+// CreateAnnotatedTag provides a mock function with given fields: _a0, _a1
+func (_m *Client) CreateAnnotatedTag(_a0 context.Context, _a1 git.CreateAnnotatedTagArgs) (*git.GitAnnotatedTag, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for CreateAnnotatedTag")
+ }
+
+ var r0 *git.GitAnnotatedTag
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.CreateAnnotatedTagArgs) (*git.GitAnnotatedTag, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.CreateAnnotatedTagArgs) *git.GitAnnotatedTag); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*git.GitAnnotatedTag)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.CreateAnnotatedTagArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// CreateAttachment provides a mock function with given fields: _a0, _a1
+func (_m *Client) CreateAttachment(_a0 context.Context, _a1 git.CreateAttachmentArgs) (*git.Attachment, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for CreateAttachment")
+ }
+
+ var r0 *git.Attachment
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.CreateAttachmentArgs) (*git.Attachment, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.CreateAttachmentArgs) *git.Attachment); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*git.Attachment)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.CreateAttachmentArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// CreateCherryPick provides a mock function with given fields: _a0, _a1
+func (_m *Client) CreateCherryPick(_a0 context.Context, _a1 git.CreateCherryPickArgs) (*git.GitCherryPick, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for CreateCherryPick")
+ }
+
+ var r0 *git.GitCherryPick
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.CreateCherryPickArgs) (*git.GitCherryPick, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.CreateCherryPickArgs) *git.GitCherryPick); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*git.GitCherryPick)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.CreateCherryPickArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// CreateComment provides a mock function with given fields: _a0, _a1
+func (_m *Client) CreateComment(_a0 context.Context, _a1 git.CreateCommentArgs) (*git.Comment, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for CreateComment")
+ }
+
+ var r0 *git.Comment
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.CreateCommentArgs) (*git.Comment, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.CreateCommentArgs) *git.Comment); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*git.Comment)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.CreateCommentArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// CreateCommitStatus provides a mock function with given fields: _a0, _a1
+func (_m *Client) CreateCommitStatus(_a0 context.Context, _a1 git.CreateCommitStatusArgs) (*git.GitStatus, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for CreateCommitStatus")
+ }
+
+ var r0 *git.GitStatus
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.CreateCommitStatusArgs) (*git.GitStatus, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.CreateCommitStatusArgs) *git.GitStatus); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*git.GitStatus)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.CreateCommitStatusArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// CreateFavorite provides a mock function with given fields: _a0, _a1
+func (_m *Client) CreateFavorite(_a0 context.Context, _a1 git.CreateFavoriteArgs) (*git.GitRefFavorite, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for CreateFavorite")
+ }
+
+ var r0 *git.GitRefFavorite
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.CreateFavoriteArgs) (*git.GitRefFavorite, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.CreateFavoriteArgs) *git.GitRefFavorite); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*git.GitRefFavorite)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.CreateFavoriteArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// CreateForkSyncRequest provides a mock function with given fields: _a0, _a1
+func (_m *Client) CreateForkSyncRequest(_a0 context.Context, _a1 git.CreateForkSyncRequestArgs) (*git.GitForkSyncRequest, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for CreateForkSyncRequest")
+ }
+
+ var r0 *git.GitForkSyncRequest
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.CreateForkSyncRequestArgs) (*git.GitForkSyncRequest, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.CreateForkSyncRequestArgs) *git.GitForkSyncRequest); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*git.GitForkSyncRequest)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.CreateForkSyncRequestArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// CreateImportRequest provides a mock function with given fields: _a0, _a1
+func (_m *Client) CreateImportRequest(_a0 context.Context, _a1 git.CreateImportRequestArgs) (*git.GitImportRequest, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for CreateImportRequest")
+ }
+
+ var r0 *git.GitImportRequest
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.CreateImportRequestArgs) (*git.GitImportRequest, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.CreateImportRequestArgs) *git.GitImportRequest); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*git.GitImportRequest)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.CreateImportRequestArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// CreateLike provides a mock function with given fields: _a0, _a1
+func (_m *Client) CreateLike(_a0 context.Context, _a1 git.CreateLikeArgs) error {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for CreateLike")
+ }
+
+ var r0 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.CreateLikeArgs) error); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ r0 = ret.Error(0)
+ }
+
+ return r0
+}
+
+// CreateMergeRequest provides a mock function with given fields: _a0, _a1
+func (_m *Client) CreateMergeRequest(_a0 context.Context, _a1 git.CreateMergeRequestArgs) (*git.GitMerge, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for CreateMergeRequest")
+ }
+
+ var r0 *git.GitMerge
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.CreateMergeRequestArgs) (*git.GitMerge, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.CreateMergeRequestArgs) *git.GitMerge); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*git.GitMerge)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.CreateMergeRequestArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// CreatePullRequest provides a mock function with given fields: _a0, _a1
+func (_m *Client) CreatePullRequest(_a0 context.Context, _a1 git.CreatePullRequestArgs) (*git.GitPullRequest, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for CreatePullRequest")
+ }
+
+ var r0 *git.GitPullRequest
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.CreatePullRequestArgs) (*git.GitPullRequest, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.CreatePullRequestArgs) *git.GitPullRequest); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*git.GitPullRequest)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.CreatePullRequestArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// CreatePullRequestIterationStatus provides a mock function with given fields: _a0, _a1
+func (_m *Client) CreatePullRequestIterationStatus(_a0 context.Context, _a1 git.CreatePullRequestIterationStatusArgs) (*git.GitPullRequestStatus, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for CreatePullRequestIterationStatus")
+ }
+
+ var r0 *git.GitPullRequestStatus
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.CreatePullRequestIterationStatusArgs) (*git.GitPullRequestStatus, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.CreatePullRequestIterationStatusArgs) *git.GitPullRequestStatus); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*git.GitPullRequestStatus)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.CreatePullRequestIterationStatusArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// CreatePullRequestLabel provides a mock function with given fields: _a0, _a1
+func (_m *Client) CreatePullRequestLabel(_a0 context.Context, _a1 git.CreatePullRequestLabelArgs) (*core.WebApiTagDefinition, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for CreatePullRequestLabel")
+ }
+
+ var r0 *core.WebApiTagDefinition
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.CreatePullRequestLabelArgs) (*core.WebApiTagDefinition, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.CreatePullRequestLabelArgs) *core.WebApiTagDefinition); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*core.WebApiTagDefinition)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.CreatePullRequestLabelArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// CreatePullRequestReviewer provides a mock function with given fields: _a0, _a1
+func (_m *Client) CreatePullRequestReviewer(_a0 context.Context, _a1 git.CreatePullRequestReviewerArgs) (*git.IdentityRefWithVote, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for CreatePullRequestReviewer")
+ }
+
+ var r0 *git.IdentityRefWithVote
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.CreatePullRequestReviewerArgs) (*git.IdentityRefWithVote, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.CreatePullRequestReviewerArgs) *git.IdentityRefWithVote); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*git.IdentityRefWithVote)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.CreatePullRequestReviewerArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// CreatePullRequestReviewers provides a mock function with given fields: _a0, _a1
+func (_m *Client) CreatePullRequestReviewers(_a0 context.Context, _a1 git.CreatePullRequestReviewersArgs) (*[]git.IdentityRefWithVote, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for CreatePullRequestReviewers")
+ }
+
+ var r0 *[]git.IdentityRefWithVote
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.CreatePullRequestReviewersArgs) (*[]git.IdentityRefWithVote, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.CreatePullRequestReviewersArgs) *[]git.IdentityRefWithVote); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*[]git.IdentityRefWithVote)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.CreatePullRequestReviewersArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// CreatePullRequestStatus provides a mock function with given fields: _a0, _a1
+func (_m *Client) CreatePullRequestStatus(_a0 context.Context, _a1 git.CreatePullRequestStatusArgs) (*git.GitPullRequestStatus, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for CreatePullRequestStatus")
+ }
+
+ var r0 *git.GitPullRequestStatus
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.CreatePullRequestStatusArgs) (*git.GitPullRequestStatus, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.CreatePullRequestStatusArgs) *git.GitPullRequestStatus); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*git.GitPullRequestStatus)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.CreatePullRequestStatusArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// CreatePush provides a mock function with given fields: _a0, _a1
+func (_m *Client) CreatePush(_a0 context.Context, _a1 git.CreatePushArgs) (*git.GitPush, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for CreatePush")
+ }
+
+ var r0 *git.GitPush
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.CreatePushArgs) (*git.GitPush, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.CreatePushArgs) *git.GitPush); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*git.GitPush)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.CreatePushArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// CreateRepository provides a mock function with given fields: _a0, _a1
+func (_m *Client) CreateRepository(_a0 context.Context, _a1 git.CreateRepositoryArgs) (*git.GitRepository, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for CreateRepository")
+ }
+
+ var r0 *git.GitRepository
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.CreateRepositoryArgs) (*git.GitRepository, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.CreateRepositoryArgs) *git.GitRepository); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*git.GitRepository)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.CreateRepositoryArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// CreateRevert provides a mock function with given fields: _a0, _a1
+func (_m *Client) CreateRevert(_a0 context.Context, _a1 git.CreateRevertArgs) (*git.GitRevert, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for CreateRevert")
+ }
+
+ var r0 *git.GitRevert
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.CreateRevertArgs) (*git.GitRevert, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.CreateRevertArgs) *git.GitRevert); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*git.GitRevert)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.CreateRevertArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// CreateThread provides a mock function with given fields: _a0, _a1
+func (_m *Client) CreateThread(_a0 context.Context, _a1 git.CreateThreadArgs) (*git.GitPullRequestCommentThread, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for CreateThread")
+ }
+
+ var r0 *git.GitPullRequestCommentThread
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.CreateThreadArgs) (*git.GitPullRequestCommentThread, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.CreateThreadArgs) *git.GitPullRequestCommentThread); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*git.GitPullRequestCommentThread)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.CreateThreadArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// DeleteAttachment provides a mock function with given fields: _a0, _a1
+func (_m *Client) DeleteAttachment(_a0 context.Context, _a1 git.DeleteAttachmentArgs) error {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for DeleteAttachment")
+ }
+
+ var r0 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.DeleteAttachmentArgs) error); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ r0 = ret.Error(0)
+ }
+
+ return r0
+}
+
+// DeleteComment provides a mock function with given fields: _a0, _a1
+func (_m *Client) DeleteComment(_a0 context.Context, _a1 git.DeleteCommentArgs) error {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for DeleteComment")
+ }
+
+ var r0 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.DeleteCommentArgs) error); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ r0 = ret.Error(0)
+ }
+
+ return r0
+}
+
+// DeleteLike provides a mock function with given fields: _a0, _a1
+func (_m *Client) DeleteLike(_a0 context.Context, _a1 git.DeleteLikeArgs) error {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for DeleteLike")
+ }
+
+ var r0 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.DeleteLikeArgs) error); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ r0 = ret.Error(0)
+ }
+
+ return r0
+}
+
+// DeletePullRequestIterationStatus provides a mock function with given fields: _a0, _a1
+func (_m *Client) DeletePullRequestIterationStatus(_a0 context.Context, _a1 git.DeletePullRequestIterationStatusArgs) error {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for DeletePullRequestIterationStatus")
+ }
+
+ var r0 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.DeletePullRequestIterationStatusArgs) error); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ r0 = ret.Error(0)
+ }
+
+ return r0
+}
+
+// DeletePullRequestLabels provides a mock function with given fields: _a0, _a1
+func (_m *Client) DeletePullRequestLabels(_a0 context.Context, _a1 git.DeletePullRequestLabelsArgs) error {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for DeletePullRequestLabels")
+ }
+
+ var r0 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.DeletePullRequestLabelsArgs) error); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ r0 = ret.Error(0)
+ }
+
+ return r0
+}
+
+// DeletePullRequestReviewer provides a mock function with given fields: _a0, _a1
+func (_m *Client) DeletePullRequestReviewer(_a0 context.Context, _a1 git.DeletePullRequestReviewerArgs) error {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for DeletePullRequestReviewer")
+ }
+
+ var r0 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.DeletePullRequestReviewerArgs) error); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ r0 = ret.Error(0)
+ }
+
+ return r0
+}
+
+// DeletePullRequestStatus provides a mock function with given fields: _a0, _a1
+func (_m *Client) DeletePullRequestStatus(_a0 context.Context, _a1 git.DeletePullRequestStatusArgs) error {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for DeletePullRequestStatus")
+ }
+
+ var r0 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.DeletePullRequestStatusArgs) error); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ r0 = ret.Error(0)
+ }
+
+ return r0
+}
+
+// DeleteRefFavorite provides a mock function with given fields: _a0, _a1
+func (_m *Client) DeleteRefFavorite(_a0 context.Context, _a1 git.DeleteRefFavoriteArgs) error {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for DeleteRefFavorite")
+ }
+
+ var r0 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.DeleteRefFavoriteArgs) error); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ r0 = ret.Error(0)
+ }
+
+ return r0
+}
+
+// DeleteRepository provides a mock function with given fields: _a0, _a1
+func (_m *Client) DeleteRepository(_a0 context.Context, _a1 git.DeleteRepositoryArgs) error {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for DeleteRepository")
+ }
+
+ var r0 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.DeleteRepositoryArgs) error); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ r0 = ret.Error(0)
+ }
+
+ return r0
+}
+
+// DeleteRepositoryFromRecycleBin provides a mock function with given fields: _a0, _a1
+func (_m *Client) DeleteRepositoryFromRecycleBin(_a0 context.Context, _a1 git.DeleteRepositoryFromRecycleBinArgs) error {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for DeleteRepositoryFromRecycleBin")
+ }
+
+ var r0 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.DeleteRepositoryFromRecycleBinArgs) error); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ r0 = ret.Error(0)
+ }
+
+ return r0
+}
+
+// GetAnnotatedTag provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetAnnotatedTag(_a0 context.Context, _a1 git.GetAnnotatedTagArgs) (*git.GitAnnotatedTag, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetAnnotatedTag")
+ }
+
+ var r0 *git.GitAnnotatedTag
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetAnnotatedTagArgs) (*git.GitAnnotatedTag, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetAnnotatedTagArgs) *git.GitAnnotatedTag); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*git.GitAnnotatedTag)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetAnnotatedTagArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetAttachmentContent provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetAttachmentContent(_a0 context.Context, _a1 git.GetAttachmentContentArgs) (io.ReadCloser, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetAttachmentContent")
+ }
+
+ var r0 io.ReadCloser
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetAttachmentContentArgs) (io.ReadCloser, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetAttachmentContentArgs) io.ReadCloser); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(io.ReadCloser)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetAttachmentContentArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetAttachmentZip provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetAttachmentZip(_a0 context.Context, _a1 git.GetAttachmentZipArgs) (io.ReadCloser, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetAttachmentZip")
+ }
+
+ var r0 io.ReadCloser
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetAttachmentZipArgs) (io.ReadCloser, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetAttachmentZipArgs) io.ReadCloser); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(io.ReadCloser)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetAttachmentZipArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetAttachments provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetAttachments(_a0 context.Context, _a1 git.GetAttachmentsArgs) (*[]git.Attachment, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetAttachments")
+ }
+
+ var r0 *[]git.Attachment
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetAttachmentsArgs) (*[]git.Attachment, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetAttachmentsArgs) *[]git.Attachment); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*[]git.Attachment)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetAttachmentsArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetBlob provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetBlob(_a0 context.Context, _a1 git.GetBlobArgs) (*git.GitBlobRef, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetBlob")
+ }
+
+ var r0 *git.GitBlobRef
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetBlobArgs) (*git.GitBlobRef, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetBlobArgs) *git.GitBlobRef); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*git.GitBlobRef)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetBlobArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetBlobContent provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetBlobContent(_a0 context.Context, _a1 git.GetBlobContentArgs) (io.ReadCloser, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetBlobContent")
+ }
+
+ var r0 io.ReadCloser
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetBlobContentArgs) (io.ReadCloser, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetBlobContentArgs) io.ReadCloser); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(io.ReadCloser)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetBlobContentArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetBlobZip provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetBlobZip(_a0 context.Context, _a1 git.GetBlobZipArgs) (io.ReadCloser, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetBlobZip")
+ }
+
+ var r0 io.ReadCloser
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetBlobZipArgs) (io.ReadCloser, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetBlobZipArgs) io.ReadCloser); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(io.ReadCloser)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetBlobZipArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetBlobsZip provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetBlobsZip(_a0 context.Context, _a1 git.GetBlobsZipArgs) (io.ReadCloser, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetBlobsZip")
+ }
+
+ var r0 io.ReadCloser
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetBlobsZipArgs) (io.ReadCloser, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetBlobsZipArgs) io.ReadCloser); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(io.ReadCloser)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetBlobsZipArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetBranch provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetBranch(_a0 context.Context, _a1 git.GetBranchArgs) (*git.GitBranchStats, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetBranch")
+ }
+
+ var r0 *git.GitBranchStats
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetBranchArgs) (*git.GitBranchStats, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetBranchArgs) *git.GitBranchStats); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*git.GitBranchStats)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetBranchArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetBranches provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetBranches(_a0 context.Context, _a1 git.GetBranchesArgs) (*[]git.GitBranchStats, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetBranches")
+ }
+
+ var r0 *[]git.GitBranchStats
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetBranchesArgs) (*[]git.GitBranchStats, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetBranchesArgs) *[]git.GitBranchStats); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*[]git.GitBranchStats)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetBranchesArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetChanges provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetChanges(_a0 context.Context, _a1 git.GetChangesArgs) (*git.GitCommitChanges, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetChanges")
+ }
+
+ var r0 *git.GitCommitChanges
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetChangesArgs) (*git.GitCommitChanges, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetChangesArgs) *git.GitCommitChanges); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*git.GitCommitChanges)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetChangesArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetCherryPick provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetCherryPick(_a0 context.Context, _a1 git.GetCherryPickArgs) (*git.GitCherryPick, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetCherryPick")
+ }
+
+ var r0 *git.GitCherryPick
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetCherryPickArgs) (*git.GitCherryPick, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetCherryPickArgs) *git.GitCherryPick); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*git.GitCherryPick)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetCherryPickArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetCherryPickForRefName provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetCherryPickForRefName(_a0 context.Context, _a1 git.GetCherryPickForRefNameArgs) (*git.GitCherryPick, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetCherryPickForRefName")
+ }
+
+ var r0 *git.GitCherryPick
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetCherryPickForRefNameArgs) (*git.GitCherryPick, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetCherryPickForRefNameArgs) *git.GitCherryPick); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*git.GitCherryPick)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetCherryPickForRefNameArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetComment provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetComment(_a0 context.Context, _a1 git.GetCommentArgs) (*git.Comment, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetComment")
+ }
+
+ var r0 *git.Comment
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetCommentArgs) (*git.Comment, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetCommentArgs) *git.Comment); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*git.Comment)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetCommentArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetComments provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetComments(_a0 context.Context, _a1 git.GetCommentsArgs) (*[]git.Comment, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetComments")
+ }
+
+ var r0 *[]git.Comment
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetCommentsArgs) (*[]git.Comment, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetCommentsArgs) *[]git.Comment); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*[]git.Comment)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetCommentsArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetCommit provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetCommit(_a0 context.Context, _a1 git.GetCommitArgs) (*git.GitCommit, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetCommit")
+ }
+
+ var r0 *git.GitCommit
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetCommitArgs) (*git.GitCommit, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetCommitArgs) *git.GitCommit); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*git.GitCommit)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetCommitArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetCommitDiffs provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetCommitDiffs(_a0 context.Context, _a1 git.GetCommitDiffsArgs) (*git.GitCommitDiffs, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetCommitDiffs")
+ }
+
+ var r0 *git.GitCommitDiffs
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetCommitDiffsArgs) (*git.GitCommitDiffs, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetCommitDiffsArgs) *git.GitCommitDiffs); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*git.GitCommitDiffs)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetCommitDiffsArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetCommits provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetCommits(_a0 context.Context, _a1 git.GetCommitsArgs) (*[]git.GitCommitRef, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetCommits")
+ }
+
+ var r0 *[]git.GitCommitRef
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetCommitsArgs) (*[]git.GitCommitRef, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetCommitsArgs) *[]git.GitCommitRef); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*[]git.GitCommitRef)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetCommitsArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetCommitsBatch provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetCommitsBatch(_a0 context.Context, _a1 git.GetCommitsBatchArgs) (*[]git.GitCommitRef, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetCommitsBatch")
+ }
+
+ var r0 *[]git.GitCommitRef
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetCommitsBatchArgs) (*[]git.GitCommitRef, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetCommitsBatchArgs) *[]git.GitCommitRef); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*[]git.GitCommitRef)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetCommitsBatchArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetDeletedRepositories provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetDeletedRepositories(_a0 context.Context, _a1 git.GetDeletedRepositoriesArgs) (*[]git.GitDeletedRepository, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetDeletedRepositories")
+ }
+
+ var r0 *[]git.GitDeletedRepository
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetDeletedRepositoriesArgs) (*[]git.GitDeletedRepository, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetDeletedRepositoriesArgs) *[]git.GitDeletedRepository); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*[]git.GitDeletedRepository)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetDeletedRepositoriesArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetForkSyncRequest provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetForkSyncRequest(_a0 context.Context, _a1 git.GetForkSyncRequestArgs) (*git.GitForkSyncRequest, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetForkSyncRequest")
+ }
+
+ var r0 *git.GitForkSyncRequest
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetForkSyncRequestArgs) (*git.GitForkSyncRequest, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetForkSyncRequestArgs) *git.GitForkSyncRequest); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*git.GitForkSyncRequest)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetForkSyncRequestArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetForkSyncRequests provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetForkSyncRequests(_a0 context.Context, _a1 git.GetForkSyncRequestsArgs) (*[]git.GitForkSyncRequest, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetForkSyncRequests")
+ }
+
+ var r0 *[]git.GitForkSyncRequest
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetForkSyncRequestsArgs) (*[]git.GitForkSyncRequest, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetForkSyncRequestsArgs) *[]git.GitForkSyncRequest); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*[]git.GitForkSyncRequest)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetForkSyncRequestsArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetForks provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetForks(_a0 context.Context, _a1 git.GetForksArgs) (*[]git.GitRepositoryRef, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetForks")
+ }
+
+ var r0 *[]git.GitRepositoryRef
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetForksArgs) (*[]git.GitRepositoryRef, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetForksArgs) *[]git.GitRepositoryRef); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*[]git.GitRepositoryRef)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetForksArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetImportRequest provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetImportRequest(_a0 context.Context, _a1 git.GetImportRequestArgs) (*git.GitImportRequest, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetImportRequest")
+ }
+
+ var r0 *git.GitImportRequest
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetImportRequestArgs) (*git.GitImportRequest, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetImportRequestArgs) *git.GitImportRequest); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*git.GitImportRequest)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetImportRequestArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetItem provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetItem(_a0 context.Context, _a1 git.GetItemArgs) (*git.GitItem, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetItem")
+ }
+
+ var r0 *git.GitItem
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetItemArgs) (*git.GitItem, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetItemArgs) *git.GitItem); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*git.GitItem)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetItemArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetItemContent provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetItemContent(_a0 context.Context, _a1 git.GetItemContentArgs) (io.ReadCloser, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetItemContent")
+ }
+
+ var r0 io.ReadCloser
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetItemContentArgs) (io.ReadCloser, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetItemContentArgs) io.ReadCloser); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(io.ReadCloser)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetItemContentArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetItemText provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetItemText(_a0 context.Context, _a1 git.GetItemTextArgs) (io.ReadCloser, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetItemText")
+ }
+
+ var r0 io.ReadCloser
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetItemTextArgs) (io.ReadCloser, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetItemTextArgs) io.ReadCloser); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(io.ReadCloser)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetItemTextArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetItemZip provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetItemZip(_a0 context.Context, _a1 git.GetItemZipArgs) (io.ReadCloser, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetItemZip")
+ }
+
+ var r0 io.ReadCloser
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetItemZipArgs) (io.ReadCloser, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetItemZipArgs) io.ReadCloser); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(io.ReadCloser)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetItemZipArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetItems provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetItems(_a0 context.Context, _a1 git.GetItemsArgs) (*[]git.GitItem, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetItems")
+ }
+
+ var r0 *[]git.GitItem
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetItemsArgs) (*[]git.GitItem, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetItemsArgs) *[]git.GitItem); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*[]git.GitItem)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetItemsArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetItemsBatch provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetItemsBatch(_a0 context.Context, _a1 git.GetItemsBatchArgs) (*[][]git.GitItem, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetItemsBatch")
+ }
+
+ var r0 *[][]git.GitItem
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetItemsBatchArgs) (*[][]git.GitItem, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetItemsBatchArgs) *[][]git.GitItem); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*[][]git.GitItem)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetItemsBatchArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetLikes provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetLikes(_a0 context.Context, _a1 git.GetLikesArgs) (*[]webapi.IdentityRef, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetLikes")
+ }
+
+ var r0 *[]webapi.IdentityRef
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetLikesArgs) (*[]webapi.IdentityRef, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetLikesArgs) *[]webapi.IdentityRef); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*[]webapi.IdentityRef)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetLikesArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetMergeBases provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetMergeBases(_a0 context.Context, _a1 git.GetMergeBasesArgs) (*[]git.GitCommitRef, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetMergeBases")
+ }
+
+ var r0 *[]git.GitCommitRef
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetMergeBasesArgs) (*[]git.GitCommitRef, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetMergeBasesArgs) *[]git.GitCommitRef); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*[]git.GitCommitRef)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetMergeBasesArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetMergeRequest provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetMergeRequest(_a0 context.Context, _a1 git.GetMergeRequestArgs) (*git.GitMerge, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetMergeRequest")
+ }
+
+ var r0 *git.GitMerge
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetMergeRequestArgs) (*git.GitMerge, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetMergeRequestArgs) *git.GitMerge); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*git.GitMerge)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetMergeRequestArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetPolicyConfigurations provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetPolicyConfigurations(_a0 context.Context, _a1 git.GetPolicyConfigurationsArgs) (*git.GitPolicyConfigurationResponse, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetPolicyConfigurations")
+ }
+
+ var r0 *git.GitPolicyConfigurationResponse
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetPolicyConfigurationsArgs) (*git.GitPolicyConfigurationResponse, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetPolicyConfigurationsArgs) *git.GitPolicyConfigurationResponse); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*git.GitPolicyConfigurationResponse)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetPolicyConfigurationsArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetPullRequest provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetPullRequest(_a0 context.Context, _a1 git.GetPullRequestArgs) (*git.GitPullRequest, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetPullRequest")
+ }
+
+ var r0 *git.GitPullRequest
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetPullRequestArgs) (*git.GitPullRequest, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetPullRequestArgs) *git.GitPullRequest); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*git.GitPullRequest)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetPullRequestArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetPullRequestById provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetPullRequestById(_a0 context.Context, _a1 git.GetPullRequestByIdArgs) (*git.GitPullRequest, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetPullRequestById")
+ }
+
+ var r0 *git.GitPullRequest
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetPullRequestByIdArgs) (*git.GitPullRequest, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetPullRequestByIdArgs) *git.GitPullRequest); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*git.GitPullRequest)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetPullRequestByIdArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetPullRequestCommits provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetPullRequestCommits(_a0 context.Context, _a1 git.GetPullRequestCommitsArgs) (*git.GetPullRequestCommitsResponseValue, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetPullRequestCommits")
+ }
+
+ var r0 *git.GetPullRequestCommitsResponseValue
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetPullRequestCommitsArgs) (*git.GetPullRequestCommitsResponseValue, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetPullRequestCommitsArgs) *git.GetPullRequestCommitsResponseValue); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*git.GetPullRequestCommitsResponseValue)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetPullRequestCommitsArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetPullRequestIteration provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetPullRequestIteration(_a0 context.Context, _a1 git.GetPullRequestIterationArgs) (*git.GitPullRequestIteration, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetPullRequestIteration")
+ }
+
+ var r0 *git.GitPullRequestIteration
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetPullRequestIterationArgs) (*git.GitPullRequestIteration, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetPullRequestIterationArgs) *git.GitPullRequestIteration); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*git.GitPullRequestIteration)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetPullRequestIterationArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetPullRequestIterationChanges provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetPullRequestIterationChanges(_a0 context.Context, _a1 git.GetPullRequestIterationChangesArgs) (*git.GitPullRequestIterationChanges, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetPullRequestIterationChanges")
+ }
+
+ var r0 *git.GitPullRequestIterationChanges
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetPullRequestIterationChangesArgs) (*git.GitPullRequestIterationChanges, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetPullRequestIterationChangesArgs) *git.GitPullRequestIterationChanges); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*git.GitPullRequestIterationChanges)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetPullRequestIterationChangesArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetPullRequestIterationCommits provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetPullRequestIterationCommits(_a0 context.Context, _a1 git.GetPullRequestIterationCommitsArgs) (*[]git.GitCommitRef, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetPullRequestIterationCommits")
+ }
+
+ var r0 *[]git.GitCommitRef
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetPullRequestIterationCommitsArgs) (*[]git.GitCommitRef, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetPullRequestIterationCommitsArgs) *[]git.GitCommitRef); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*[]git.GitCommitRef)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetPullRequestIterationCommitsArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetPullRequestIterationStatus provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetPullRequestIterationStatus(_a0 context.Context, _a1 git.GetPullRequestIterationStatusArgs) (*git.GitPullRequestStatus, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetPullRequestIterationStatus")
+ }
+
+ var r0 *git.GitPullRequestStatus
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetPullRequestIterationStatusArgs) (*git.GitPullRequestStatus, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetPullRequestIterationStatusArgs) *git.GitPullRequestStatus); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*git.GitPullRequestStatus)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetPullRequestIterationStatusArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetPullRequestIterationStatuses provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetPullRequestIterationStatuses(_a0 context.Context, _a1 git.GetPullRequestIterationStatusesArgs) (*[]git.GitPullRequestStatus, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetPullRequestIterationStatuses")
+ }
+
+ var r0 *[]git.GitPullRequestStatus
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetPullRequestIterationStatusesArgs) (*[]git.GitPullRequestStatus, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetPullRequestIterationStatusesArgs) *[]git.GitPullRequestStatus); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*[]git.GitPullRequestStatus)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetPullRequestIterationStatusesArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetPullRequestIterations provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetPullRequestIterations(_a0 context.Context, _a1 git.GetPullRequestIterationsArgs) (*[]git.GitPullRequestIteration, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetPullRequestIterations")
+ }
+
+ var r0 *[]git.GitPullRequestIteration
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetPullRequestIterationsArgs) (*[]git.GitPullRequestIteration, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetPullRequestIterationsArgs) *[]git.GitPullRequestIteration); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*[]git.GitPullRequestIteration)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetPullRequestIterationsArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetPullRequestLabel provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetPullRequestLabel(_a0 context.Context, _a1 git.GetPullRequestLabelArgs) (*core.WebApiTagDefinition, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetPullRequestLabel")
+ }
+
+ var r0 *core.WebApiTagDefinition
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetPullRequestLabelArgs) (*core.WebApiTagDefinition, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetPullRequestLabelArgs) *core.WebApiTagDefinition); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*core.WebApiTagDefinition)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetPullRequestLabelArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetPullRequestLabels provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetPullRequestLabels(_a0 context.Context, _a1 git.GetPullRequestLabelsArgs) (*[]core.WebApiTagDefinition, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetPullRequestLabels")
+ }
+
+ var r0 *[]core.WebApiTagDefinition
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetPullRequestLabelsArgs) (*[]core.WebApiTagDefinition, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetPullRequestLabelsArgs) *[]core.WebApiTagDefinition); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*[]core.WebApiTagDefinition)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetPullRequestLabelsArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetPullRequestProperties provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetPullRequestProperties(_a0 context.Context, _a1 git.GetPullRequestPropertiesArgs) (interface{}, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetPullRequestProperties")
+ }
+
+ var r0 interface{}
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetPullRequestPropertiesArgs) (interface{}, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetPullRequestPropertiesArgs) interface{}); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(interface{})
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetPullRequestPropertiesArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetPullRequestQuery provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetPullRequestQuery(_a0 context.Context, _a1 git.GetPullRequestQueryArgs) (*git.GitPullRequestQuery, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetPullRequestQuery")
+ }
+
+ var r0 *git.GitPullRequestQuery
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetPullRequestQueryArgs) (*git.GitPullRequestQuery, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetPullRequestQueryArgs) *git.GitPullRequestQuery); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*git.GitPullRequestQuery)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetPullRequestQueryArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetPullRequestReviewer provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetPullRequestReviewer(_a0 context.Context, _a1 git.GetPullRequestReviewerArgs) (*git.IdentityRefWithVote, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetPullRequestReviewer")
+ }
+
+ var r0 *git.IdentityRefWithVote
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetPullRequestReviewerArgs) (*git.IdentityRefWithVote, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetPullRequestReviewerArgs) *git.IdentityRefWithVote); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*git.IdentityRefWithVote)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetPullRequestReviewerArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetPullRequestReviewers provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetPullRequestReviewers(_a0 context.Context, _a1 git.GetPullRequestReviewersArgs) (*[]git.IdentityRefWithVote, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetPullRequestReviewers")
+ }
+
+ var r0 *[]git.IdentityRefWithVote
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetPullRequestReviewersArgs) (*[]git.IdentityRefWithVote, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetPullRequestReviewersArgs) *[]git.IdentityRefWithVote); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*[]git.IdentityRefWithVote)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetPullRequestReviewersArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetPullRequestStatus provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetPullRequestStatus(_a0 context.Context, _a1 git.GetPullRequestStatusArgs) (*git.GitPullRequestStatus, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetPullRequestStatus")
+ }
+
+ var r0 *git.GitPullRequestStatus
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetPullRequestStatusArgs) (*git.GitPullRequestStatus, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetPullRequestStatusArgs) *git.GitPullRequestStatus); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*git.GitPullRequestStatus)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetPullRequestStatusArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetPullRequestStatuses provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetPullRequestStatuses(_a0 context.Context, _a1 git.GetPullRequestStatusesArgs) (*[]git.GitPullRequestStatus, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetPullRequestStatuses")
+ }
+
+ var r0 *[]git.GitPullRequestStatus
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetPullRequestStatusesArgs) (*[]git.GitPullRequestStatus, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetPullRequestStatusesArgs) *[]git.GitPullRequestStatus); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*[]git.GitPullRequestStatus)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetPullRequestStatusesArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetPullRequestThread provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetPullRequestThread(_a0 context.Context, _a1 git.GetPullRequestThreadArgs) (*git.GitPullRequestCommentThread, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetPullRequestThread")
+ }
+
+ var r0 *git.GitPullRequestCommentThread
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetPullRequestThreadArgs) (*git.GitPullRequestCommentThread, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetPullRequestThreadArgs) *git.GitPullRequestCommentThread); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*git.GitPullRequestCommentThread)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetPullRequestThreadArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetPullRequestWorkItemRefs provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetPullRequestWorkItemRefs(_a0 context.Context, _a1 git.GetPullRequestWorkItemRefsArgs) (*[]webapi.ResourceRef, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetPullRequestWorkItemRefs")
+ }
+
+ var r0 *[]webapi.ResourceRef
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetPullRequestWorkItemRefsArgs) (*[]webapi.ResourceRef, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetPullRequestWorkItemRefsArgs) *[]webapi.ResourceRef); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*[]webapi.ResourceRef)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetPullRequestWorkItemRefsArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetPullRequests provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetPullRequests(_a0 context.Context, _a1 git.GetPullRequestsArgs) (*[]git.GitPullRequest, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetPullRequests")
+ }
+
+ var r0 *[]git.GitPullRequest
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetPullRequestsArgs) (*[]git.GitPullRequest, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetPullRequestsArgs) *[]git.GitPullRequest); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*[]git.GitPullRequest)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetPullRequestsArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetPullRequestsByProject provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetPullRequestsByProject(_a0 context.Context, _a1 git.GetPullRequestsByProjectArgs) (*[]git.GitPullRequest, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetPullRequestsByProject")
+ }
+
+ var r0 *[]git.GitPullRequest
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetPullRequestsByProjectArgs) (*[]git.GitPullRequest, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetPullRequestsByProjectArgs) *[]git.GitPullRequest); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*[]git.GitPullRequest)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetPullRequestsByProjectArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetPush provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetPush(_a0 context.Context, _a1 git.GetPushArgs) (*git.GitPush, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetPush")
+ }
+
+ var r0 *git.GitPush
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetPushArgs) (*git.GitPush, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetPushArgs) *git.GitPush); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*git.GitPush)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetPushArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetPushCommits provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetPushCommits(_a0 context.Context, _a1 git.GetPushCommitsArgs) (*[]git.GitCommitRef, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetPushCommits")
+ }
+
+ var r0 *[]git.GitCommitRef
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetPushCommitsArgs) (*[]git.GitCommitRef, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetPushCommitsArgs) *[]git.GitCommitRef); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*[]git.GitCommitRef)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetPushCommitsArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetPushes provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetPushes(_a0 context.Context, _a1 git.GetPushesArgs) (*[]git.GitPush, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetPushes")
+ }
+
+ var r0 *[]git.GitPush
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetPushesArgs) (*[]git.GitPush, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetPushesArgs) *[]git.GitPush); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*[]git.GitPush)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetPushesArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetRecycleBinRepositories provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetRecycleBinRepositories(_a0 context.Context, _a1 git.GetRecycleBinRepositoriesArgs) (*[]git.GitDeletedRepository, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetRecycleBinRepositories")
+ }
+
+ var r0 *[]git.GitDeletedRepository
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetRecycleBinRepositoriesArgs) (*[]git.GitDeletedRepository, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetRecycleBinRepositoriesArgs) *[]git.GitDeletedRepository); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*[]git.GitDeletedRepository)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetRecycleBinRepositoriesArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetRefFavorite provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetRefFavorite(_a0 context.Context, _a1 git.GetRefFavoriteArgs) (*git.GitRefFavorite, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetRefFavorite")
+ }
+
+ var r0 *git.GitRefFavorite
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetRefFavoriteArgs) (*git.GitRefFavorite, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetRefFavoriteArgs) *git.GitRefFavorite); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*git.GitRefFavorite)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetRefFavoriteArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetRefFavorites provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetRefFavorites(_a0 context.Context, _a1 git.GetRefFavoritesArgs) (*[]git.GitRefFavorite, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetRefFavorites")
+ }
+
+ var r0 *[]git.GitRefFavorite
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetRefFavoritesArgs) (*[]git.GitRefFavorite, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetRefFavoritesArgs) *[]git.GitRefFavorite); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*[]git.GitRefFavorite)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetRefFavoritesArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetRefs provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetRefs(_a0 context.Context, _a1 git.GetRefsArgs) (*git.GetRefsResponseValue, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetRefs")
+ }
+
+ var r0 *git.GetRefsResponseValue
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetRefsArgs) (*git.GetRefsResponseValue, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetRefsArgs) *git.GetRefsResponseValue); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*git.GetRefsResponseValue)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetRefsArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetRepositories provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetRepositories(_a0 context.Context, _a1 git.GetRepositoriesArgs) (*[]git.GitRepository, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetRepositories")
+ }
+
+ var r0 *[]git.GitRepository
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetRepositoriesArgs) (*[]git.GitRepository, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetRepositoriesArgs) *[]git.GitRepository); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*[]git.GitRepository)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetRepositoriesArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetRepository provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetRepository(_a0 context.Context, _a1 git.GetRepositoryArgs) (*git.GitRepository, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetRepository")
+ }
+
+ var r0 *git.GitRepository
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetRepositoryArgs) (*git.GitRepository, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetRepositoryArgs) *git.GitRepository); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*git.GitRepository)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetRepositoryArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetRepositoryWithParent provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetRepositoryWithParent(_a0 context.Context, _a1 git.GetRepositoryWithParentArgs) (*git.GitRepository, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetRepositoryWithParent")
+ }
+
+ var r0 *git.GitRepository
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetRepositoryWithParentArgs) (*git.GitRepository, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetRepositoryWithParentArgs) *git.GitRepository); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*git.GitRepository)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetRepositoryWithParentArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetRevert provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetRevert(_a0 context.Context, _a1 git.GetRevertArgs) (*git.GitRevert, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetRevert")
+ }
+
+ var r0 *git.GitRevert
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetRevertArgs) (*git.GitRevert, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetRevertArgs) *git.GitRevert); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*git.GitRevert)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetRevertArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetRevertForRefName provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetRevertForRefName(_a0 context.Context, _a1 git.GetRevertForRefNameArgs) (*git.GitRevert, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetRevertForRefName")
+ }
+
+ var r0 *git.GitRevert
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetRevertForRefNameArgs) (*git.GitRevert, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetRevertForRefNameArgs) *git.GitRevert); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*git.GitRevert)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetRevertForRefNameArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetStatuses provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetStatuses(_a0 context.Context, _a1 git.GetStatusesArgs) (*[]git.GitStatus, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetStatuses")
+ }
+
+ var r0 *[]git.GitStatus
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetStatusesArgs) (*[]git.GitStatus, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetStatusesArgs) *[]git.GitStatus); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*[]git.GitStatus)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetStatusesArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetSuggestions provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetSuggestions(_a0 context.Context, _a1 git.GetSuggestionsArgs) (*[]git.GitSuggestion, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetSuggestions")
+ }
+
+ var r0 *[]git.GitSuggestion
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetSuggestionsArgs) (*[]git.GitSuggestion, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetSuggestionsArgs) *[]git.GitSuggestion); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*[]git.GitSuggestion)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetSuggestionsArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetThreads provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetThreads(_a0 context.Context, _a1 git.GetThreadsArgs) (*[]git.GitPullRequestCommentThread, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetThreads")
+ }
+
+ var r0 *[]git.GitPullRequestCommentThread
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetThreadsArgs) (*[]git.GitPullRequestCommentThread, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetThreadsArgs) *[]git.GitPullRequestCommentThread); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*[]git.GitPullRequestCommentThread)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetThreadsArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetTree provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetTree(_a0 context.Context, _a1 git.GetTreeArgs) (*git.GitTreeRef, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetTree")
+ }
+
+ var r0 *git.GitTreeRef
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetTreeArgs) (*git.GitTreeRef, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetTreeArgs) *git.GitTreeRef); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*git.GitTreeRef)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetTreeArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetTreeZip provides a mock function with given fields: _a0, _a1
+func (_m *Client) GetTreeZip(_a0 context.Context, _a1 git.GetTreeZipArgs) (io.ReadCloser, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetTreeZip")
+ }
+
+ var r0 io.ReadCloser
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetTreeZipArgs) (io.ReadCloser, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.GetTreeZipArgs) io.ReadCloser); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(io.ReadCloser)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.GetTreeZipArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// QueryImportRequests provides a mock function with given fields: _a0, _a1
+func (_m *Client) QueryImportRequests(_a0 context.Context, _a1 git.QueryImportRequestsArgs) (*[]git.GitImportRequest, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for QueryImportRequests")
+ }
+
+ var r0 *[]git.GitImportRequest
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.QueryImportRequestsArgs) (*[]git.GitImportRequest, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.QueryImportRequestsArgs) *[]git.GitImportRequest); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*[]git.GitImportRequest)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.QueryImportRequestsArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// RestoreRepositoryFromRecycleBin provides a mock function with given fields: _a0, _a1
+func (_m *Client) RestoreRepositoryFromRecycleBin(_a0 context.Context, _a1 git.RestoreRepositoryFromRecycleBinArgs) (*git.GitRepository, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for RestoreRepositoryFromRecycleBin")
+ }
+
+ var r0 *git.GitRepository
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.RestoreRepositoryFromRecycleBinArgs) (*git.GitRepository, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.RestoreRepositoryFromRecycleBinArgs) *git.GitRepository); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*git.GitRepository)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.RestoreRepositoryFromRecycleBinArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// SharePullRequest provides a mock function with given fields: _a0, _a1
+func (_m *Client) SharePullRequest(_a0 context.Context, _a1 git.SharePullRequestArgs) error {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for SharePullRequest")
+ }
+
+ var r0 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.SharePullRequestArgs) error); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ r0 = ret.Error(0)
+ }
+
+ return r0
+}
+
+// UpdateComment provides a mock function with given fields: _a0, _a1
+func (_m *Client) UpdateComment(_a0 context.Context, _a1 git.UpdateCommentArgs) (*git.Comment, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for UpdateComment")
+ }
+
+ var r0 *git.Comment
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.UpdateCommentArgs) (*git.Comment, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.UpdateCommentArgs) *git.Comment); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*git.Comment)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.UpdateCommentArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// UpdateImportRequest provides a mock function with given fields: _a0, _a1
+func (_m *Client) UpdateImportRequest(_a0 context.Context, _a1 git.UpdateImportRequestArgs) (*git.GitImportRequest, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for UpdateImportRequest")
+ }
+
+ var r0 *git.GitImportRequest
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.UpdateImportRequestArgs) (*git.GitImportRequest, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.UpdateImportRequestArgs) *git.GitImportRequest); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*git.GitImportRequest)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.UpdateImportRequestArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// UpdatePullRequest provides a mock function with given fields: _a0, _a1
+func (_m *Client) UpdatePullRequest(_a0 context.Context, _a1 git.UpdatePullRequestArgs) (*git.GitPullRequest, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for UpdatePullRequest")
+ }
+
+ var r0 *git.GitPullRequest
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.UpdatePullRequestArgs) (*git.GitPullRequest, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.UpdatePullRequestArgs) *git.GitPullRequest); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*git.GitPullRequest)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.UpdatePullRequestArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// UpdatePullRequestIterationStatuses provides a mock function with given fields: _a0, _a1
+func (_m *Client) UpdatePullRequestIterationStatuses(_a0 context.Context, _a1 git.UpdatePullRequestIterationStatusesArgs) error {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for UpdatePullRequestIterationStatuses")
+ }
+
+ var r0 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.UpdatePullRequestIterationStatusesArgs) error); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ r0 = ret.Error(0)
+ }
+
+ return r0
+}
+
+// UpdatePullRequestProperties provides a mock function with given fields: _a0, _a1
+func (_m *Client) UpdatePullRequestProperties(_a0 context.Context, _a1 git.UpdatePullRequestPropertiesArgs) (interface{}, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for UpdatePullRequestProperties")
+ }
+
+ var r0 interface{}
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.UpdatePullRequestPropertiesArgs) (interface{}, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.UpdatePullRequestPropertiesArgs) interface{}); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(interface{})
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.UpdatePullRequestPropertiesArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// UpdatePullRequestReviewers provides a mock function with given fields: _a0, _a1
+func (_m *Client) UpdatePullRequestReviewers(_a0 context.Context, _a1 git.UpdatePullRequestReviewersArgs) error {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for UpdatePullRequestReviewers")
+ }
+
+ var r0 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.UpdatePullRequestReviewersArgs) error); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ r0 = ret.Error(0)
+ }
+
+ return r0
+}
+
+// UpdatePullRequestStatuses provides a mock function with given fields: _a0, _a1
+func (_m *Client) UpdatePullRequestStatuses(_a0 context.Context, _a1 git.UpdatePullRequestStatusesArgs) error {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for UpdatePullRequestStatuses")
+ }
+
+ var r0 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.UpdatePullRequestStatusesArgs) error); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ r0 = ret.Error(0)
+ }
+
+ return r0
+}
+
+// UpdateRef provides a mock function with given fields: _a0, _a1
+func (_m *Client) UpdateRef(_a0 context.Context, _a1 git.UpdateRefArgs) (*git.GitRef, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for UpdateRef")
+ }
+
+ var r0 *git.GitRef
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.UpdateRefArgs) (*git.GitRef, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.UpdateRefArgs) *git.GitRef); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*git.GitRef)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.UpdateRefArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// UpdateRefs provides a mock function with given fields: _a0, _a1
+func (_m *Client) UpdateRefs(_a0 context.Context, _a1 git.UpdateRefsArgs) (*[]git.GitRefUpdateResult, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for UpdateRefs")
+ }
+
+ var r0 *[]git.GitRefUpdateResult
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.UpdateRefsArgs) (*[]git.GitRefUpdateResult, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.UpdateRefsArgs) *[]git.GitRefUpdateResult); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*[]git.GitRefUpdateResult)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.UpdateRefsArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// UpdateRepository provides a mock function with given fields: _a0, _a1
+func (_m *Client) UpdateRepository(_a0 context.Context, _a1 git.UpdateRepositoryArgs) (*git.GitRepository, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for UpdateRepository")
+ }
+
+ var r0 *git.GitRepository
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.UpdateRepositoryArgs) (*git.GitRepository, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.UpdateRepositoryArgs) *git.GitRepository); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*git.GitRepository)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.UpdateRepositoryArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// UpdateThread provides a mock function with given fields: _a0, _a1
+func (_m *Client) UpdateThread(_a0 context.Context, _a1 git.UpdateThreadArgs) (*git.GitPullRequestCommentThread, error) {
+ ret := _m.Called(_a0, _a1)
+
+ if len(ret) == 0 {
+ panic("no return value specified for UpdateThread")
+ }
+
+ var r0 *git.GitPullRequestCommentThread
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, git.UpdateThreadArgs) (*git.GitPullRequestCommentThread, error)); ok {
+ return rf(_a0, _a1)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, git.UpdateThreadArgs) *git.GitPullRequestCommentThread); ok {
+ r0 = rf(_a0, _a1)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*git.GitPullRequestCommentThread)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, git.UpdateThreadArgs) error); ok {
+ r1 = rf(_a0, _a1)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
// NewClient creates a new instance of Client. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
// The first argument is typically a *testing.T value.
func NewClient(t interface {
@@ -27,6634 +3333,3 @@ func NewClient(t interface {
return mock
}
-
-// Client is an autogenerated mock type for the Client type
-type Client struct {
- mock.Mock
-}
-
-type Client_Expecter struct {
- mock *mock.Mock
-}
-
-func (_m *Client) EXPECT() *Client_Expecter {
- return &Client_Expecter{mock: &_m.Mock}
-}
-
-// CreateAnnotatedTag provides a mock function for the type Client
-func (_mock *Client) CreateAnnotatedTag(context1 context.Context, createAnnotatedTagArgs git.CreateAnnotatedTagArgs) (*git.GitAnnotatedTag, error) {
- ret := _mock.Called(context1, createAnnotatedTagArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for CreateAnnotatedTag")
- }
-
- var r0 *git.GitAnnotatedTag
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.CreateAnnotatedTagArgs) (*git.GitAnnotatedTag, error)); ok {
- return returnFunc(context1, createAnnotatedTagArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.CreateAnnotatedTagArgs) *git.GitAnnotatedTag); ok {
- r0 = returnFunc(context1, createAnnotatedTagArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*git.GitAnnotatedTag)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.CreateAnnotatedTagArgs) error); ok {
- r1 = returnFunc(context1, createAnnotatedTagArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_CreateAnnotatedTag_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CreateAnnotatedTag'
-type Client_CreateAnnotatedTag_Call struct {
- *mock.Call
-}
-
-// CreateAnnotatedTag is a helper method to define mock.On call
-// - context1
-// - createAnnotatedTagArgs
-func (_e *Client_Expecter) CreateAnnotatedTag(context1 interface{}, createAnnotatedTagArgs interface{}) *Client_CreateAnnotatedTag_Call {
- return &Client_CreateAnnotatedTag_Call{Call: _e.mock.On("CreateAnnotatedTag", context1, createAnnotatedTagArgs)}
-}
-
-func (_c *Client_CreateAnnotatedTag_Call) Run(run func(context1 context.Context, createAnnotatedTagArgs git.CreateAnnotatedTagArgs)) *Client_CreateAnnotatedTag_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.CreateAnnotatedTagArgs))
- })
- return _c
-}
-
-func (_c *Client_CreateAnnotatedTag_Call) Return(gitAnnotatedTag *git.GitAnnotatedTag, err error) *Client_CreateAnnotatedTag_Call {
- _c.Call.Return(gitAnnotatedTag, err)
- return _c
-}
-
-func (_c *Client_CreateAnnotatedTag_Call) RunAndReturn(run func(context1 context.Context, createAnnotatedTagArgs git.CreateAnnotatedTagArgs) (*git.GitAnnotatedTag, error)) *Client_CreateAnnotatedTag_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// CreateAttachment provides a mock function for the type Client
-func (_mock *Client) CreateAttachment(context1 context.Context, createAttachmentArgs git.CreateAttachmentArgs) (*git.Attachment, error) {
- ret := _mock.Called(context1, createAttachmentArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for CreateAttachment")
- }
-
- var r0 *git.Attachment
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.CreateAttachmentArgs) (*git.Attachment, error)); ok {
- return returnFunc(context1, createAttachmentArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.CreateAttachmentArgs) *git.Attachment); ok {
- r0 = returnFunc(context1, createAttachmentArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*git.Attachment)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.CreateAttachmentArgs) error); ok {
- r1 = returnFunc(context1, createAttachmentArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_CreateAttachment_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CreateAttachment'
-type Client_CreateAttachment_Call struct {
- *mock.Call
-}
-
-// CreateAttachment is a helper method to define mock.On call
-// - context1
-// - createAttachmentArgs
-func (_e *Client_Expecter) CreateAttachment(context1 interface{}, createAttachmentArgs interface{}) *Client_CreateAttachment_Call {
- return &Client_CreateAttachment_Call{Call: _e.mock.On("CreateAttachment", context1, createAttachmentArgs)}
-}
-
-func (_c *Client_CreateAttachment_Call) Run(run func(context1 context.Context, createAttachmentArgs git.CreateAttachmentArgs)) *Client_CreateAttachment_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.CreateAttachmentArgs))
- })
- return _c
-}
-
-func (_c *Client_CreateAttachment_Call) Return(attachment *git.Attachment, err error) *Client_CreateAttachment_Call {
- _c.Call.Return(attachment, err)
- return _c
-}
-
-func (_c *Client_CreateAttachment_Call) RunAndReturn(run func(context1 context.Context, createAttachmentArgs git.CreateAttachmentArgs) (*git.Attachment, error)) *Client_CreateAttachment_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// CreateCherryPick provides a mock function for the type Client
-func (_mock *Client) CreateCherryPick(context1 context.Context, createCherryPickArgs git.CreateCherryPickArgs) (*git.GitCherryPick, error) {
- ret := _mock.Called(context1, createCherryPickArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for CreateCherryPick")
- }
-
- var r0 *git.GitCherryPick
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.CreateCherryPickArgs) (*git.GitCherryPick, error)); ok {
- return returnFunc(context1, createCherryPickArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.CreateCherryPickArgs) *git.GitCherryPick); ok {
- r0 = returnFunc(context1, createCherryPickArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*git.GitCherryPick)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.CreateCherryPickArgs) error); ok {
- r1 = returnFunc(context1, createCherryPickArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_CreateCherryPick_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CreateCherryPick'
-type Client_CreateCherryPick_Call struct {
- *mock.Call
-}
-
-// CreateCherryPick is a helper method to define mock.On call
-// - context1
-// - createCherryPickArgs
-func (_e *Client_Expecter) CreateCherryPick(context1 interface{}, createCherryPickArgs interface{}) *Client_CreateCherryPick_Call {
- return &Client_CreateCherryPick_Call{Call: _e.mock.On("CreateCherryPick", context1, createCherryPickArgs)}
-}
-
-func (_c *Client_CreateCherryPick_Call) Run(run func(context1 context.Context, createCherryPickArgs git.CreateCherryPickArgs)) *Client_CreateCherryPick_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.CreateCherryPickArgs))
- })
- return _c
-}
-
-func (_c *Client_CreateCherryPick_Call) Return(gitCherryPick *git.GitCherryPick, err error) *Client_CreateCherryPick_Call {
- _c.Call.Return(gitCherryPick, err)
- return _c
-}
-
-func (_c *Client_CreateCherryPick_Call) RunAndReturn(run func(context1 context.Context, createCherryPickArgs git.CreateCherryPickArgs) (*git.GitCherryPick, error)) *Client_CreateCherryPick_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// CreateComment provides a mock function for the type Client
-func (_mock *Client) CreateComment(context1 context.Context, createCommentArgs git.CreateCommentArgs) (*git.Comment, error) {
- ret := _mock.Called(context1, createCommentArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for CreateComment")
- }
-
- var r0 *git.Comment
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.CreateCommentArgs) (*git.Comment, error)); ok {
- return returnFunc(context1, createCommentArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.CreateCommentArgs) *git.Comment); ok {
- r0 = returnFunc(context1, createCommentArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*git.Comment)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.CreateCommentArgs) error); ok {
- r1 = returnFunc(context1, createCommentArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_CreateComment_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CreateComment'
-type Client_CreateComment_Call struct {
- *mock.Call
-}
-
-// CreateComment is a helper method to define mock.On call
-// - context1
-// - createCommentArgs
-func (_e *Client_Expecter) CreateComment(context1 interface{}, createCommentArgs interface{}) *Client_CreateComment_Call {
- return &Client_CreateComment_Call{Call: _e.mock.On("CreateComment", context1, createCommentArgs)}
-}
-
-func (_c *Client_CreateComment_Call) Run(run func(context1 context.Context, createCommentArgs git.CreateCommentArgs)) *Client_CreateComment_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.CreateCommentArgs))
- })
- return _c
-}
-
-func (_c *Client_CreateComment_Call) Return(comment *git.Comment, err error) *Client_CreateComment_Call {
- _c.Call.Return(comment, err)
- return _c
-}
-
-func (_c *Client_CreateComment_Call) RunAndReturn(run func(context1 context.Context, createCommentArgs git.CreateCommentArgs) (*git.Comment, error)) *Client_CreateComment_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// CreateCommitStatus provides a mock function for the type Client
-func (_mock *Client) CreateCommitStatus(context1 context.Context, createCommitStatusArgs git.CreateCommitStatusArgs) (*git.GitStatus, error) {
- ret := _mock.Called(context1, createCommitStatusArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for CreateCommitStatus")
- }
-
- var r0 *git.GitStatus
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.CreateCommitStatusArgs) (*git.GitStatus, error)); ok {
- return returnFunc(context1, createCommitStatusArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.CreateCommitStatusArgs) *git.GitStatus); ok {
- r0 = returnFunc(context1, createCommitStatusArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*git.GitStatus)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.CreateCommitStatusArgs) error); ok {
- r1 = returnFunc(context1, createCommitStatusArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_CreateCommitStatus_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CreateCommitStatus'
-type Client_CreateCommitStatus_Call struct {
- *mock.Call
-}
-
-// CreateCommitStatus is a helper method to define mock.On call
-// - context1
-// - createCommitStatusArgs
-func (_e *Client_Expecter) CreateCommitStatus(context1 interface{}, createCommitStatusArgs interface{}) *Client_CreateCommitStatus_Call {
- return &Client_CreateCommitStatus_Call{Call: _e.mock.On("CreateCommitStatus", context1, createCommitStatusArgs)}
-}
-
-func (_c *Client_CreateCommitStatus_Call) Run(run func(context1 context.Context, createCommitStatusArgs git.CreateCommitStatusArgs)) *Client_CreateCommitStatus_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.CreateCommitStatusArgs))
- })
- return _c
-}
-
-func (_c *Client_CreateCommitStatus_Call) Return(gitStatus *git.GitStatus, err error) *Client_CreateCommitStatus_Call {
- _c.Call.Return(gitStatus, err)
- return _c
-}
-
-func (_c *Client_CreateCommitStatus_Call) RunAndReturn(run func(context1 context.Context, createCommitStatusArgs git.CreateCommitStatusArgs) (*git.GitStatus, error)) *Client_CreateCommitStatus_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// CreateFavorite provides a mock function for the type Client
-func (_mock *Client) CreateFavorite(context1 context.Context, createFavoriteArgs git.CreateFavoriteArgs) (*git.GitRefFavorite, error) {
- ret := _mock.Called(context1, createFavoriteArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for CreateFavorite")
- }
-
- var r0 *git.GitRefFavorite
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.CreateFavoriteArgs) (*git.GitRefFavorite, error)); ok {
- return returnFunc(context1, createFavoriteArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.CreateFavoriteArgs) *git.GitRefFavorite); ok {
- r0 = returnFunc(context1, createFavoriteArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*git.GitRefFavorite)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.CreateFavoriteArgs) error); ok {
- r1 = returnFunc(context1, createFavoriteArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_CreateFavorite_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CreateFavorite'
-type Client_CreateFavorite_Call struct {
- *mock.Call
-}
-
-// CreateFavorite is a helper method to define mock.On call
-// - context1
-// - createFavoriteArgs
-func (_e *Client_Expecter) CreateFavorite(context1 interface{}, createFavoriteArgs interface{}) *Client_CreateFavorite_Call {
- return &Client_CreateFavorite_Call{Call: _e.mock.On("CreateFavorite", context1, createFavoriteArgs)}
-}
-
-func (_c *Client_CreateFavorite_Call) Run(run func(context1 context.Context, createFavoriteArgs git.CreateFavoriteArgs)) *Client_CreateFavorite_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.CreateFavoriteArgs))
- })
- return _c
-}
-
-func (_c *Client_CreateFavorite_Call) Return(gitRefFavorite *git.GitRefFavorite, err error) *Client_CreateFavorite_Call {
- _c.Call.Return(gitRefFavorite, err)
- return _c
-}
-
-func (_c *Client_CreateFavorite_Call) RunAndReturn(run func(context1 context.Context, createFavoriteArgs git.CreateFavoriteArgs) (*git.GitRefFavorite, error)) *Client_CreateFavorite_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// CreateForkSyncRequest provides a mock function for the type Client
-func (_mock *Client) CreateForkSyncRequest(context1 context.Context, createForkSyncRequestArgs git.CreateForkSyncRequestArgs) (*git.GitForkSyncRequest, error) {
- ret := _mock.Called(context1, createForkSyncRequestArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for CreateForkSyncRequest")
- }
-
- var r0 *git.GitForkSyncRequest
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.CreateForkSyncRequestArgs) (*git.GitForkSyncRequest, error)); ok {
- return returnFunc(context1, createForkSyncRequestArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.CreateForkSyncRequestArgs) *git.GitForkSyncRequest); ok {
- r0 = returnFunc(context1, createForkSyncRequestArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*git.GitForkSyncRequest)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.CreateForkSyncRequestArgs) error); ok {
- r1 = returnFunc(context1, createForkSyncRequestArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_CreateForkSyncRequest_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CreateForkSyncRequest'
-type Client_CreateForkSyncRequest_Call struct {
- *mock.Call
-}
-
-// CreateForkSyncRequest is a helper method to define mock.On call
-// - context1
-// - createForkSyncRequestArgs
-func (_e *Client_Expecter) CreateForkSyncRequest(context1 interface{}, createForkSyncRequestArgs interface{}) *Client_CreateForkSyncRequest_Call {
- return &Client_CreateForkSyncRequest_Call{Call: _e.mock.On("CreateForkSyncRequest", context1, createForkSyncRequestArgs)}
-}
-
-func (_c *Client_CreateForkSyncRequest_Call) Run(run func(context1 context.Context, createForkSyncRequestArgs git.CreateForkSyncRequestArgs)) *Client_CreateForkSyncRequest_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.CreateForkSyncRequestArgs))
- })
- return _c
-}
-
-func (_c *Client_CreateForkSyncRequest_Call) Return(gitForkSyncRequest *git.GitForkSyncRequest, err error) *Client_CreateForkSyncRequest_Call {
- _c.Call.Return(gitForkSyncRequest, err)
- return _c
-}
-
-func (_c *Client_CreateForkSyncRequest_Call) RunAndReturn(run func(context1 context.Context, createForkSyncRequestArgs git.CreateForkSyncRequestArgs) (*git.GitForkSyncRequest, error)) *Client_CreateForkSyncRequest_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// CreateImportRequest provides a mock function for the type Client
-func (_mock *Client) CreateImportRequest(context1 context.Context, createImportRequestArgs git.CreateImportRequestArgs) (*git.GitImportRequest, error) {
- ret := _mock.Called(context1, createImportRequestArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for CreateImportRequest")
- }
-
- var r0 *git.GitImportRequest
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.CreateImportRequestArgs) (*git.GitImportRequest, error)); ok {
- return returnFunc(context1, createImportRequestArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.CreateImportRequestArgs) *git.GitImportRequest); ok {
- r0 = returnFunc(context1, createImportRequestArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*git.GitImportRequest)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.CreateImportRequestArgs) error); ok {
- r1 = returnFunc(context1, createImportRequestArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_CreateImportRequest_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CreateImportRequest'
-type Client_CreateImportRequest_Call struct {
- *mock.Call
-}
-
-// CreateImportRequest is a helper method to define mock.On call
-// - context1
-// - createImportRequestArgs
-func (_e *Client_Expecter) CreateImportRequest(context1 interface{}, createImportRequestArgs interface{}) *Client_CreateImportRequest_Call {
- return &Client_CreateImportRequest_Call{Call: _e.mock.On("CreateImportRequest", context1, createImportRequestArgs)}
-}
-
-func (_c *Client_CreateImportRequest_Call) Run(run func(context1 context.Context, createImportRequestArgs git.CreateImportRequestArgs)) *Client_CreateImportRequest_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.CreateImportRequestArgs))
- })
- return _c
-}
-
-func (_c *Client_CreateImportRequest_Call) Return(gitImportRequest *git.GitImportRequest, err error) *Client_CreateImportRequest_Call {
- _c.Call.Return(gitImportRequest, err)
- return _c
-}
-
-func (_c *Client_CreateImportRequest_Call) RunAndReturn(run func(context1 context.Context, createImportRequestArgs git.CreateImportRequestArgs) (*git.GitImportRequest, error)) *Client_CreateImportRequest_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// CreateLike provides a mock function for the type Client
-func (_mock *Client) CreateLike(context1 context.Context, createLikeArgs git.CreateLikeArgs) error {
- ret := _mock.Called(context1, createLikeArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for CreateLike")
- }
-
- var r0 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.CreateLikeArgs) error); ok {
- r0 = returnFunc(context1, createLikeArgs)
- } else {
- r0 = ret.Error(0)
- }
- return r0
-}
-
-// Client_CreateLike_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CreateLike'
-type Client_CreateLike_Call struct {
- *mock.Call
-}
-
-// CreateLike is a helper method to define mock.On call
-// - context1
-// - createLikeArgs
-func (_e *Client_Expecter) CreateLike(context1 interface{}, createLikeArgs interface{}) *Client_CreateLike_Call {
- return &Client_CreateLike_Call{Call: _e.mock.On("CreateLike", context1, createLikeArgs)}
-}
-
-func (_c *Client_CreateLike_Call) Run(run func(context1 context.Context, createLikeArgs git.CreateLikeArgs)) *Client_CreateLike_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.CreateLikeArgs))
- })
- return _c
-}
-
-func (_c *Client_CreateLike_Call) Return(err error) *Client_CreateLike_Call {
- _c.Call.Return(err)
- return _c
-}
-
-func (_c *Client_CreateLike_Call) RunAndReturn(run func(context1 context.Context, createLikeArgs git.CreateLikeArgs) error) *Client_CreateLike_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// CreateMergeRequest provides a mock function for the type Client
-func (_mock *Client) CreateMergeRequest(context1 context.Context, createMergeRequestArgs git.CreateMergeRequestArgs) (*git.GitMerge, error) {
- ret := _mock.Called(context1, createMergeRequestArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for CreateMergeRequest")
- }
-
- var r0 *git.GitMerge
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.CreateMergeRequestArgs) (*git.GitMerge, error)); ok {
- return returnFunc(context1, createMergeRequestArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.CreateMergeRequestArgs) *git.GitMerge); ok {
- r0 = returnFunc(context1, createMergeRequestArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*git.GitMerge)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.CreateMergeRequestArgs) error); ok {
- r1 = returnFunc(context1, createMergeRequestArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_CreateMergeRequest_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CreateMergeRequest'
-type Client_CreateMergeRequest_Call struct {
- *mock.Call
-}
-
-// CreateMergeRequest is a helper method to define mock.On call
-// - context1
-// - createMergeRequestArgs
-func (_e *Client_Expecter) CreateMergeRequest(context1 interface{}, createMergeRequestArgs interface{}) *Client_CreateMergeRequest_Call {
- return &Client_CreateMergeRequest_Call{Call: _e.mock.On("CreateMergeRequest", context1, createMergeRequestArgs)}
-}
-
-func (_c *Client_CreateMergeRequest_Call) Run(run func(context1 context.Context, createMergeRequestArgs git.CreateMergeRequestArgs)) *Client_CreateMergeRequest_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.CreateMergeRequestArgs))
- })
- return _c
-}
-
-func (_c *Client_CreateMergeRequest_Call) Return(gitMerge *git.GitMerge, err error) *Client_CreateMergeRequest_Call {
- _c.Call.Return(gitMerge, err)
- return _c
-}
-
-func (_c *Client_CreateMergeRequest_Call) RunAndReturn(run func(context1 context.Context, createMergeRequestArgs git.CreateMergeRequestArgs) (*git.GitMerge, error)) *Client_CreateMergeRequest_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// CreatePullRequest provides a mock function for the type Client
-func (_mock *Client) CreatePullRequest(context1 context.Context, createPullRequestArgs git.CreatePullRequestArgs) (*git.GitPullRequest, error) {
- ret := _mock.Called(context1, createPullRequestArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for CreatePullRequest")
- }
-
- var r0 *git.GitPullRequest
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.CreatePullRequestArgs) (*git.GitPullRequest, error)); ok {
- return returnFunc(context1, createPullRequestArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.CreatePullRequestArgs) *git.GitPullRequest); ok {
- r0 = returnFunc(context1, createPullRequestArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*git.GitPullRequest)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.CreatePullRequestArgs) error); ok {
- r1 = returnFunc(context1, createPullRequestArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_CreatePullRequest_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CreatePullRequest'
-type Client_CreatePullRequest_Call struct {
- *mock.Call
-}
-
-// CreatePullRequest is a helper method to define mock.On call
-// - context1
-// - createPullRequestArgs
-func (_e *Client_Expecter) CreatePullRequest(context1 interface{}, createPullRequestArgs interface{}) *Client_CreatePullRequest_Call {
- return &Client_CreatePullRequest_Call{Call: _e.mock.On("CreatePullRequest", context1, createPullRequestArgs)}
-}
-
-func (_c *Client_CreatePullRequest_Call) Run(run func(context1 context.Context, createPullRequestArgs git.CreatePullRequestArgs)) *Client_CreatePullRequest_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.CreatePullRequestArgs))
- })
- return _c
-}
-
-func (_c *Client_CreatePullRequest_Call) Return(gitPullRequest *git.GitPullRequest, err error) *Client_CreatePullRequest_Call {
- _c.Call.Return(gitPullRequest, err)
- return _c
-}
-
-func (_c *Client_CreatePullRequest_Call) RunAndReturn(run func(context1 context.Context, createPullRequestArgs git.CreatePullRequestArgs) (*git.GitPullRequest, error)) *Client_CreatePullRequest_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// CreatePullRequestIterationStatus provides a mock function for the type Client
-func (_mock *Client) CreatePullRequestIterationStatus(context1 context.Context, createPullRequestIterationStatusArgs git.CreatePullRequestIterationStatusArgs) (*git.GitPullRequestStatus, error) {
- ret := _mock.Called(context1, createPullRequestIterationStatusArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for CreatePullRequestIterationStatus")
- }
-
- var r0 *git.GitPullRequestStatus
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.CreatePullRequestIterationStatusArgs) (*git.GitPullRequestStatus, error)); ok {
- return returnFunc(context1, createPullRequestIterationStatusArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.CreatePullRequestIterationStatusArgs) *git.GitPullRequestStatus); ok {
- r0 = returnFunc(context1, createPullRequestIterationStatusArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*git.GitPullRequestStatus)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.CreatePullRequestIterationStatusArgs) error); ok {
- r1 = returnFunc(context1, createPullRequestIterationStatusArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_CreatePullRequestIterationStatus_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CreatePullRequestIterationStatus'
-type Client_CreatePullRequestIterationStatus_Call struct {
- *mock.Call
-}
-
-// CreatePullRequestIterationStatus is a helper method to define mock.On call
-// - context1
-// - createPullRequestIterationStatusArgs
-func (_e *Client_Expecter) CreatePullRequestIterationStatus(context1 interface{}, createPullRequestIterationStatusArgs interface{}) *Client_CreatePullRequestIterationStatus_Call {
- return &Client_CreatePullRequestIterationStatus_Call{Call: _e.mock.On("CreatePullRequestIterationStatus", context1, createPullRequestIterationStatusArgs)}
-}
-
-func (_c *Client_CreatePullRequestIterationStatus_Call) Run(run func(context1 context.Context, createPullRequestIterationStatusArgs git.CreatePullRequestIterationStatusArgs)) *Client_CreatePullRequestIterationStatus_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.CreatePullRequestIterationStatusArgs))
- })
- return _c
-}
-
-func (_c *Client_CreatePullRequestIterationStatus_Call) Return(gitPullRequestStatus *git.GitPullRequestStatus, err error) *Client_CreatePullRequestIterationStatus_Call {
- _c.Call.Return(gitPullRequestStatus, err)
- return _c
-}
-
-func (_c *Client_CreatePullRequestIterationStatus_Call) RunAndReturn(run func(context1 context.Context, createPullRequestIterationStatusArgs git.CreatePullRequestIterationStatusArgs) (*git.GitPullRequestStatus, error)) *Client_CreatePullRequestIterationStatus_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// CreatePullRequestLabel provides a mock function for the type Client
-func (_mock *Client) CreatePullRequestLabel(context1 context.Context, createPullRequestLabelArgs git.CreatePullRequestLabelArgs) (*core.WebApiTagDefinition, error) {
- ret := _mock.Called(context1, createPullRequestLabelArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for CreatePullRequestLabel")
- }
-
- var r0 *core.WebApiTagDefinition
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.CreatePullRequestLabelArgs) (*core.WebApiTagDefinition, error)); ok {
- return returnFunc(context1, createPullRequestLabelArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.CreatePullRequestLabelArgs) *core.WebApiTagDefinition); ok {
- r0 = returnFunc(context1, createPullRequestLabelArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*core.WebApiTagDefinition)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.CreatePullRequestLabelArgs) error); ok {
- r1 = returnFunc(context1, createPullRequestLabelArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_CreatePullRequestLabel_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CreatePullRequestLabel'
-type Client_CreatePullRequestLabel_Call struct {
- *mock.Call
-}
-
-// CreatePullRequestLabel is a helper method to define mock.On call
-// - context1
-// - createPullRequestLabelArgs
-func (_e *Client_Expecter) CreatePullRequestLabel(context1 interface{}, createPullRequestLabelArgs interface{}) *Client_CreatePullRequestLabel_Call {
- return &Client_CreatePullRequestLabel_Call{Call: _e.mock.On("CreatePullRequestLabel", context1, createPullRequestLabelArgs)}
-}
-
-func (_c *Client_CreatePullRequestLabel_Call) Run(run func(context1 context.Context, createPullRequestLabelArgs git.CreatePullRequestLabelArgs)) *Client_CreatePullRequestLabel_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.CreatePullRequestLabelArgs))
- })
- return _c
-}
-
-func (_c *Client_CreatePullRequestLabel_Call) Return(webApiTagDefinition *core.WebApiTagDefinition, err error) *Client_CreatePullRequestLabel_Call {
- _c.Call.Return(webApiTagDefinition, err)
- return _c
-}
-
-func (_c *Client_CreatePullRequestLabel_Call) RunAndReturn(run func(context1 context.Context, createPullRequestLabelArgs git.CreatePullRequestLabelArgs) (*core.WebApiTagDefinition, error)) *Client_CreatePullRequestLabel_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// CreatePullRequestReviewer provides a mock function for the type Client
-func (_mock *Client) CreatePullRequestReviewer(context1 context.Context, createPullRequestReviewerArgs git.CreatePullRequestReviewerArgs) (*git.IdentityRefWithVote, error) {
- ret := _mock.Called(context1, createPullRequestReviewerArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for CreatePullRequestReviewer")
- }
-
- var r0 *git.IdentityRefWithVote
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.CreatePullRequestReviewerArgs) (*git.IdentityRefWithVote, error)); ok {
- return returnFunc(context1, createPullRequestReviewerArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.CreatePullRequestReviewerArgs) *git.IdentityRefWithVote); ok {
- r0 = returnFunc(context1, createPullRequestReviewerArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*git.IdentityRefWithVote)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.CreatePullRequestReviewerArgs) error); ok {
- r1 = returnFunc(context1, createPullRequestReviewerArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_CreatePullRequestReviewer_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CreatePullRequestReviewer'
-type Client_CreatePullRequestReviewer_Call struct {
- *mock.Call
-}
-
-// CreatePullRequestReviewer is a helper method to define mock.On call
-// - context1
-// - createPullRequestReviewerArgs
-func (_e *Client_Expecter) CreatePullRequestReviewer(context1 interface{}, createPullRequestReviewerArgs interface{}) *Client_CreatePullRequestReviewer_Call {
- return &Client_CreatePullRequestReviewer_Call{Call: _e.mock.On("CreatePullRequestReviewer", context1, createPullRequestReviewerArgs)}
-}
-
-func (_c *Client_CreatePullRequestReviewer_Call) Run(run func(context1 context.Context, createPullRequestReviewerArgs git.CreatePullRequestReviewerArgs)) *Client_CreatePullRequestReviewer_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.CreatePullRequestReviewerArgs))
- })
- return _c
-}
-
-func (_c *Client_CreatePullRequestReviewer_Call) Return(identityRefWithVote *git.IdentityRefWithVote, err error) *Client_CreatePullRequestReviewer_Call {
- _c.Call.Return(identityRefWithVote, err)
- return _c
-}
-
-func (_c *Client_CreatePullRequestReviewer_Call) RunAndReturn(run func(context1 context.Context, createPullRequestReviewerArgs git.CreatePullRequestReviewerArgs) (*git.IdentityRefWithVote, error)) *Client_CreatePullRequestReviewer_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// CreatePullRequestReviewers provides a mock function for the type Client
-func (_mock *Client) CreatePullRequestReviewers(context1 context.Context, createPullRequestReviewersArgs git.CreatePullRequestReviewersArgs) (*[]git.IdentityRefWithVote, error) {
- ret := _mock.Called(context1, createPullRequestReviewersArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for CreatePullRequestReviewers")
- }
-
- var r0 *[]git.IdentityRefWithVote
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.CreatePullRequestReviewersArgs) (*[]git.IdentityRefWithVote, error)); ok {
- return returnFunc(context1, createPullRequestReviewersArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.CreatePullRequestReviewersArgs) *[]git.IdentityRefWithVote); ok {
- r0 = returnFunc(context1, createPullRequestReviewersArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*[]git.IdentityRefWithVote)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.CreatePullRequestReviewersArgs) error); ok {
- r1 = returnFunc(context1, createPullRequestReviewersArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_CreatePullRequestReviewers_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CreatePullRequestReviewers'
-type Client_CreatePullRequestReviewers_Call struct {
- *mock.Call
-}
-
-// CreatePullRequestReviewers is a helper method to define mock.On call
-// - context1
-// - createPullRequestReviewersArgs
-func (_e *Client_Expecter) CreatePullRequestReviewers(context1 interface{}, createPullRequestReviewersArgs interface{}) *Client_CreatePullRequestReviewers_Call {
- return &Client_CreatePullRequestReviewers_Call{Call: _e.mock.On("CreatePullRequestReviewers", context1, createPullRequestReviewersArgs)}
-}
-
-func (_c *Client_CreatePullRequestReviewers_Call) Run(run func(context1 context.Context, createPullRequestReviewersArgs git.CreatePullRequestReviewersArgs)) *Client_CreatePullRequestReviewers_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.CreatePullRequestReviewersArgs))
- })
- return _c
-}
-
-func (_c *Client_CreatePullRequestReviewers_Call) Return(identityRefWithVotes *[]git.IdentityRefWithVote, err error) *Client_CreatePullRequestReviewers_Call {
- _c.Call.Return(identityRefWithVotes, err)
- return _c
-}
-
-func (_c *Client_CreatePullRequestReviewers_Call) RunAndReturn(run func(context1 context.Context, createPullRequestReviewersArgs git.CreatePullRequestReviewersArgs) (*[]git.IdentityRefWithVote, error)) *Client_CreatePullRequestReviewers_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// CreatePullRequestStatus provides a mock function for the type Client
-func (_mock *Client) CreatePullRequestStatus(context1 context.Context, createPullRequestStatusArgs git.CreatePullRequestStatusArgs) (*git.GitPullRequestStatus, error) {
- ret := _mock.Called(context1, createPullRequestStatusArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for CreatePullRequestStatus")
- }
-
- var r0 *git.GitPullRequestStatus
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.CreatePullRequestStatusArgs) (*git.GitPullRequestStatus, error)); ok {
- return returnFunc(context1, createPullRequestStatusArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.CreatePullRequestStatusArgs) *git.GitPullRequestStatus); ok {
- r0 = returnFunc(context1, createPullRequestStatusArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*git.GitPullRequestStatus)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.CreatePullRequestStatusArgs) error); ok {
- r1 = returnFunc(context1, createPullRequestStatusArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_CreatePullRequestStatus_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CreatePullRequestStatus'
-type Client_CreatePullRequestStatus_Call struct {
- *mock.Call
-}
-
-// CreatePullRequestStatus is a helper method to define mock.On call
-// - context1
-// - createPullRequestStatusArgs
-func (_e *Client_Expecter) CreatePullRequestStatus(context1 interface{}, createPullRequestStatusArgs interface{}) *Client_CreatePullRequestStatus_Call {
- return &Client_CreatePullRequestStatus_Call{Call: _e.mock.On("CreatePullRequestStatus", context1, createPullRequestStatusArgs)}
-}
-
-func (_c *Client_CreatePullRequestStatus_Call) Run(run func(context1 context.Context, createPullRequestStatusArgs git.CreatePullRequestStatusArgs)) *Client_CreatePullRequestStatus_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.CreatePullRequestStatusArgs))
- })
- return _c
-}
-
-func (_c *Client_CreatePullRequestStatus_Call) Return(gitPullRequestStatus *git.GitPullRequestStatus, err error) *Client_CreatePullRequestStatus_Call {
- _c.Call.Return(gitPullRequestStatus, err)
- return _c
-}
-
-func (_c *Client_CreatePullRequestStatus_Call) RunAndReturn(run func(context1 context.Context, createPullRequestStatusArgs git.CreatePullRequestStatusArgs) (*git.GitPullRequestStatus, error)) *Client_CreatePullRequestStatus_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// CreatePush provides a mock function for the type Client
-func (_mock *Client) CreatePush(context1 context.Context, createPushArgs git.CreatePushArgs) (*git.GitPush, error) {
- ret := _mock.Called(context1, createPushArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for CreatePush")
- }
-
- var r0 *git.GitPush
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.CreatePushArgs) (*git.GitPush, error)); ok {
- return returnFunc(context1, createPushArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.CreatePushArgs) *git.GitPush); ok {
- r0 = returnFunc(context1, createPushArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*git.GitPush)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.CreatePushArgs) error); ok {
- r1 = returnFunc(context1, createPushArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_CreatePush_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CreatePush'
-type Client_CreatePush_Call struct {
- *mock.Call
-}
-
-// CreatePush is a helper method to define mock.On call
-// - context1
-// - createPushArgs
-func (_e *Client_Expecter) CreatePush(context1 interface{}, createPushArgs interface{}) *Client_CreatePush_Call {
- return &Client_CreatePush_Call{Call: _e.mock.On("CreatePush", context1, createPushArgs)}
-}
-
-func (_c *Client_CreatePush_Call) Run(run func(context1 context.Context, createPushArgs git.CreatePushArgs)) *Client_CreatePush_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.CreatePushArgs))
- })
- return _c
-}
-
-func (_c *Client_CreatePush_Call) Return(gitPush *git.GitPush, err error) *Client_CreatePush_Call {
- _c.Call.Return(gitPush, err)
- return _c
-}
-
-func (_c *Client_CreatePush_Call) RunAndReturn(run func(context1 context.Context, createPushArgs git.CreatePushArgs) (*git.GitPush, error)) *Client_CreatePush_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// CreateRepository provides a mock function for the type Client
-func (_mock *Client) CreateRepository(context1 context.Context, createRepositoryArgs git.CreateRepositoryArgs) (*git.GitRepository, error) {
- ret := _mock.Called(context1, createRepositoryArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for CreateRepository")
- }
-
- var r0 *git.GitRepository
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.CreateRepositoryArgs) (*git.GitRepository, error)); ok {
- return returnFunc(context1, createRepositoryArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.CreateRepositoryArgs) *git.GitRepository); ok {
- r0 = returnFunc(context1, createRepositoryArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*git.GitRepository)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.CreateRepositoryArgs) error); ok {
- r1 = returnFunc(context1, createRepositoryArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_CreateRepository_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CreateRepository'
-type Client_CreateRepository_Call struct {
- *mock.Call
-}
-
-// CreateRepository is a helper method to define mock.On call
-// - context1
-// - createRepositoryArgs
-func (_e *Client_Expecter) CreateRepository(context1 interface{}, createRepositoryArgs interface{}) *Client_CreateRepository_Call {
- return &Client_CreateRepository_Call{Call: _e.mock.On("CreateRepository", context1, createRepositoryArgs)}
-}
-
-func (_c *Client_CreateRepository_Call) Run(run func(context1 context.Context, createRepositoryArgs git.CreateRepositoryArgs)) *Client_CreateRepository_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.CreateRepositoryArgs))
- })
- return _c
-}
-
-func (_c *Client_CreateRepository_Call) Return(gitRepository *git.GitRepository, err error) *Client_CreateRepository_Call {
- _c.Call.Return(gitRepository, err)
- return _c
-}
-
-func (_c *Client_CreateRepository_Call) RunAndReturn(run func(context1 context.Context, createRepositoryArgs git.CreateRepositoryArgs) (*git.GitRepository, error)) *Client_CreateRepository_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// CreateRevert provides a mock function for the type Client
-func (_mock *Client) CreateRevert(context1 context.Context, createRevertArgs git.CreateRevertArgs) (*git.GitRevert, error) {
- ret := _mock.Called(context1, createRevertArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for CreateRevert")
- }
-
- var r0 *git.GitRevert
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.CreateRevertArgs) (*git.GitRevert, error)); ok {
- return returnFunc(context1, createRevertArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.CreateRevertArgs) *git.GitRevert); ok {
- r0 = returnFunc(context1, createRevertArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*git.GitRevert)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.CreateRevertArgs) error); ok {
- r1 = returnFunc(context1, createRevertArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_CreateRevert_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CreateRevert'
-type Client_CreateRevert_Call struct {
- *mock.Call
-}
-
-// CreateRevert is a helper method to define mock.On call
-// - context1
-// - createRevertArgs
-func (_e *Client_Expecter) CreateRevert(context1 interface{}, createRevertArgs interface{}) *Client_CreateRevert_Call {
- return &Client_CreateRevert_Call{Call: _e.mock.On("CreateRevert", context1, createRevertArgs)}
-}
-
-func (_c *Client_CreateRevert_Call) Run(run func(context1 context.Context, createRevertArgs git.CreateRevertArgs)) *Client_CreateRevert_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.CreateRevertArgs))
- })
- return _c
-}
-
-func (_c *Client_CreateRevert_Call) Return(gitRevert *git.GitRevert, err error) *Client_CreateRevert_Call {
- _c.Call.Return(gitRevert, err)
- return _c
-}
-
-func (_c *Client_CreateRevert_Call) RunAndReturn(run func(context1 context.Context, createRevertArgs git.CreateRevertArgs) (*git.GitRevert, error)) *Client_CreateRevert_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// CreateThread provides a mock function for the type Client
-func (_mock *Client) CreateThread(context1 context.Context, createThreadArgs git.CreateThreadArgs) (*git.GitPullRequestCommentThread, error) {
- ret := _mock.Called(context1, createThreadArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for CreateThread")
- }
-
- var r0 *git.GitPullRequestCommentThread
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.CreateThreadArgs) (*git.GitPullRequestCommentThread, error)); ok {
- return returnFunc(context1, createThreadArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.CreateThreadArgs) *git.GitPullRequestCommentThread); ok {
- r0 = returnFunc(context1, createThreadArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*git.GitPullRequestCommentThread)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.CreateThreadArgs) error); ok {
- r1 = returnFunc(context1, createThreadArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_CreateThread_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CreateThread'
-type Client_CreateThread_Call struct {
- *mock.Call
-}
-
-// CreateThread is a helper method to define mock.On call
-// - context1
-// - createThreadArgs
-func (_e *Client_Expecter) CreateThread(context1 interface{}, createThreadArgs interface{}) *Client_CreateThread_Call {
- return &Client_CreateThread_Call{Call: _e.mock.On("CreateThread", context1, createThreadArgs)}
-}
-
-func (_c *Client_CreateThread_Call) Run(run func(context1 context.Context, createThreadArgs git.CreateThreadArgs)) *Client_CreateThread_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.CreateThreadArgs))
- })
- return _c
-}
-
-func (_c *Client_CreateThread_Call) Return(gitPullRequestCommentThread *git.GitPullRequestCommentThread, err error) *Client_CreateThread_Call {
- _c.Call.Return(gitPullRequestCommentThread, err)
- return _c
-}
-
-func (_c *Client_CreateThread_Call) RunAndReturn(run func(context1 context.Context, createThreadArgs git.CreateThreadArgs) (*git.GitPullRequestCommentThread, error)) *Client_CreateThread_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// CreateUnmaterializedPullRequestReviewer provides a mock function for the type Client
-func (_mock *Client) CreateUnmaterializedPullRequestReviewer(context1 context.Context, createUnmaterializedPullRequestReviewerArgs git.CreateUnmaterializedPullRequestReviewerArgs) (*git.IdentityRefWithVote, error) {
- ret := _mock.Called(context1, createUnmaterializedPullRequestReviewerArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for CreateUnmaterializedPullRequestReviewer")
- }
-
- var r0 *git.IdentityRefWithVote
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.CreateUnmaterializedPullRequestReviewerArgs) (*git.IdentityRefWithVote, error)); ok {
- return returnFunc(context1, createUnmaterializedPullRequestReviewerArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.CreateUnmaterializedPullRequestReviewerArgs) *git.IdentityRefWithVote); ok {
- r0 = returnFunc(context1, createUnmaterializedPullRequestReviewerArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*git.IdentityRefWithVote)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.CreateUnmaterializedPullRequestReviewerArgs) error); ok {
- r1 = returnFunc(context1, createUnmaterializedPullRequestReviewerArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_CreateUnmaterializedPullRequestReviewer_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CreateUnmaterializedPullRequestReviewer'
-type Client_CreateUnmaterializedPullRequestReviewer_Call struct {
- *mock.Call
-}
-
-// CreateUnmaterializedPullRequestReviewer is a helper method to define mock.On call
-// - context1
-// - createUnmaterializedPullRequestReviewerArgs
-func (_e *Client_Expecter) CreateUnmaterializedPullRequestReviewer(context1 interface{}, createUnmaterializedPullRequestReviewerArgs interface{}) *Client_CreateUnmaterializedPullRequestReviewer_Call {
- return &Client_CreateUnmaterializedPullRequestReviewer_Call{Call: _e.mock.On("CreateUnmaterializedPullRequestReviewer", context1, createUnmaterializedPullRequestReviewerArgs)}
-}
-
-func (_c *Client_CreateUnmaterializedPullRequestReviewer_Call) Run(run func(context1 context.Context, createUnmaterializedPullRequestReviewerArgs git.CreateUnmaterializedPullRequestReviewerArgs)) *Client_CreateUnmaterializedPullRequestReviewer_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.CreateUnmaterializedPullRequestReviewerArgs))
- })
- return _c
-}
-
-func (_c *Client_CreateUnmaterializedPullRequestReviewer_Call) Return(identityRefWithVote *git.IdentityRefWithVote, err error) *Client_CreateUnmaterializedPullRequestReviewer_Call {
- _c.Call.Return(identityRefWithVote, err)
- return _c
-}
-
-func (_c *Client_CreateUnmaterializedPullRequestReviewer_Call) RunAndReturn(run func(context1 context.Context, createUnmaterializedPullRequestReviewerArgs git.CreateUnmaterializedPullRequestReviewerArgs) (*git.IdentityRefWithVote, error)) *Client_CreateUnmaterializedPullRequestReviewer_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// DeleteAttachment provides a mock function for the type Client
-func (_mock *Client) DeleteAttachment(context1 context.Context, deleteAttachmentArgs git.DeleteAttachmentArgs) error {
- ret := _mock.Called(context1, deleteAttachmentArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for DeleteAttachment")
- }
-
- var r0 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.DeleteAttachmentArgs) error); ok {
- r0 = returnFunc(context1, deleteAttachmentArgs)
- } else {
- r0 = ret.Error(0)
- }
- return r0
-}
-
-// Client_DeleteAttachment_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DeleteAttachment'
-type Client_DeleteAttachment_Call struct {
- *mock.Call
-}
-
-// DeleteAttachment is a helper method to define mock.On call
-// - context1
-// - deleteAttachmentArgs
-func (_e *Client_Expecter) DeleteAttachment(context1 interface{}, deleteAttachmentArgs interface{}) *Client_DeleteAttachment_Call {
- return &Client_DeleteAttachment_Call{Call: _e.mock.On("DeleteAttachment", context1, deleteAttachmentArgs)}
-}
-
-func (_c *Client_DeleteAttachment_Call) Run(run func(context1 context.Context, deleteAttachmentArgs git.DeleteAttachmentArgs)) *Client_DeleteAttachment_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.DeleteAttachmentArgs))
- })
- return _c
-}
-
-func (_c *Client_DeleteAttachment_Call) Return(err error) *Client_DeleteAttachment_Call {
- _c.Call.Return(err)
- return _c
-}
-
-func (_c *Client_DeleteAttachment_Call) RunAndReturn(run func(context1 context.Context, deleteAttachmentArgs git.DeleteAttachmentArgs) error) *Client_DeleteAttachment_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// DeleteComment provides a mock function for the type Client
-func (_mock *Client) DeleteComment(context1 context.Context, deleteCommentArgs git.DeleteCommentArgs) error {
- ret := _mock.Called(context1, deleteCommentArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for DeleteComment")
- }
-
- var r0 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.DeleteCommentArgs) error); ok {
- r0 = returnFunc(context1, deleteCommentArgs)
- } else {
- r0 = ret.Error(0)
- }
- return r0
-}
-
-// Client_DeleteComment_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DeleteComment'
-type Client_DeleteComment_Call struct {
- *mock.Call
-}
-
-// DeleteComment is a helper method to define mock.On call
-// - context1
-// - deleteCommentArgs
-func (_e *Client_Expecter) DeleteComment(context1 interface{}, deleteCommentArgs interface{}) *Client_DeleteComment_Call {
- return &Client_DeleteComment_Call{Call: _e.mock.On("DeleteComment", context1, deleteCommentArgs)}
-}
-
-func (_c *Client_DeleteComment_Call) Run(run func(context1 context.Context, deleteCommentArgs git.DeleteCommentArgs)) *Client_DeleteComment_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.DeleteCommentArgs))
- })
- return _c
-}
-
-func (_c *Client_DeleteComment_Call) Return(err error) *Client_DeleteComment_Call {
- _c.Call.Return(err)
- return _c
-}
-
-func (_c *Client_DeleteComment_Call) RunAndReturn(run func(context1 context.Context, deleteCommentArgs git.DeleteCommentArgs) error) *Client_DeleteComment_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// DeleteLike provides a mock function for the type Client
-func (_mock *Client) DeleteLike(context1 context.Context, deleteLikeArgs git.DeleteLikeArgs) error {
- ret := _mock.Called(context1, deleteLikeArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for DeleteLike")
- }
-
- var r0 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.DeleteLikeArgs) error); ok {
- r0 = returnFunc(context1, deleteLikeArgs)
- } else {
- r0 = ret.Error(0)
- }
- return r0
-}
-
-// Client_DeleteLike_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DeleteLike'
-type Client_DeleteLike_Call struct {
- *mock.Call
-}
-
-// DeleteLike is a helper method to define mock.On call
-// - context1
-// - deleteLikeArgs
-func (_e *Client_Expecter) DeleteLike(context1 interface{}, deleteLikeArgs interface{}) *Client_DeleteLike_Call {
- return &Client_DeleteLike_Call{Call: _e.mock.On("DeleteLike", context1, deleteLikeArgs)}
-}
-
-func (_c *Client_DeleteLike_Call) Run(run func(context1 context.Context, deleteLikeArgs git.DeleteLikeArgs)) *Client_DeleteLike_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.DeleteLikeArgs))
- })
- return _c
-}
-
-func (_c *Client_DeleteLike_Call) Return(err error) *Client_DeleteLike_Call {
- _c.Call.Return(err)
- return _c
-}
-
-func (_c *Client_DeleteLike_Call) RunAndReturn(run func(context1 context.Context, deleteLikeArgs git.DeleteLikeArgs) error) *Client_DeleteLike_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// DeletePullRequestIterationStatus provides a mock function for the type Client
-func (_mock *Client) DeletePullRequestIterationStatus(context1 context.Context, deletePullRequestIterationStatusArgs git.DeletePullRequestIterationStatusArgs) error {
- ret := _mock.Called(context1, deletePullRequestIterationStatusArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for DeletePullRequestIterationStatus")
- }
-
- var r0 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.DeletePullRequestIterationStatusArgs) error); ok {
- r0 = returnFunc(context1, deletePullRequestIterationStatusArgs)
- } else {
- r0 = ret.Error(0)
- }
- return r0
-}
-
-// Client_DeletePullRequestIterationStatus_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DeletePullRequestIterationStatus'
-type Client_DeletePullRequestIterationStatus_Call struct {
- *mock.Call
-}
-
-// DeletePullRequestIterationStatus is a helper method to define mock.On call
-// - context1
-// - deletePullRequestIterationStatusArgs
-func (_e *Client_Expecter) DeletePullRequestIterationStatus(context1 interface{}, deletePullRequestIterationStatusArgs interface{}) *Client_DeletePullRequestIterationStatus_Call {
- return &Client_DeletePullRequestIterationStatus_Call{Call: _e.mock.On("DeletePullRequestIterationStatus", context1, deletePullRequestIterationStatusArgs)}
-}
-
-func (_c *Client_DeletePullRequestIterationStatus_Call) Run(run func(context1 context.Context, deletePullRequestIterationStatusArgs git.DeletePullRequestIterationStatusArgs)) *Client_DeletePullRequestIterationStatus_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.DeletePullRequestIterationStatusArgs))
- })
- return _c
-}
-
-func (_c *Client_DeletePullRequestIterationStatus_Call) Return(err error) *Client_DeletePullRequestIterationStatus_Call {
- _c.Call.Return(err)
- return _c
-}
-
-func (_c *Client_DeletePullRequestIterationStatus_Call) RunAndReturn(run func(context1 context.Context, deletePullRequestIterationStatusArgs git.DeletePullRequestIterationStatusArgs) error) *Client_DeletePullRequestIterationStatus_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// DeletePullRequestLabels provides a mock function for the type Client
-func (_mock *Client) DeletePullRequestLabels(context1 context.Context, deletePullRequestLabelsArgs git.DeletePullRequestLabelsArgs) error {
- ret := _mock.Called(context1, deletePullRequestLabelsArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for DeletePullRequestLabels")
- }
-
- var r0 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.DeletePullRequestLabelsArgs) error); ok {
- r0 = returnFunc(context1, deletePullRequestLabelsArgs)
- } else {
- r0 = ret.Error(0)
- }
- return r0
-}
-
-// Client_DeletePullRequestLabels_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DeletePullRequestLabels'
-type Client_DeletePullRequestLabels_Call struct {
- *mock.Call
-}
-
-// DeletePullRequestLabels is a helper method to define mock.On call
-// - context1
-// - deletePullRequestLabelsArgs
-func (_e *Client_Expecter) DeletePullRequestLabels(context1 interface{}, deletePullRequestLabelsArgs interface{}) *Client_DeletePullRequestLabels_Call {
- return &Client_DeletePullRequestLabels_Call{Call: _e.mock.On("DeletePullRequestLabels", context1, deletePullRequestLabelsArgs)}
-}
-
-func (_c *Client_DeletePullRequestLabels_Call) Run(run func(context1 context.Context, deletePullRequestLabelsArgs git.DeletePullRequestLabelsArgs)) *Client_DeletePullRequestLabels_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.DeletePullRequestLabelsArgs))
- })
- return _c
-}
-
-func (_c *Client_DeletePullRequestLabels_Call) Return(err error) *Client_DeletePullRequestLabels_Call {
- _c.Call.Return(err)
- return _c
-}
-
-func (_c *Client_DeletePullRequestLabels_Call) RunAndReturn(run func(context1 context.Context, deletePullRequestLabelsArgs git.DeletePullRequestLabelsArgs) error) *Client_DeletePullRequestLabels_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// DeletePullRequestReviewer provides a mock function for the type Client
-func (_mock *Client) DeletePullRequestReviewer(context1 context.Context, deletePullRequestReviewerArgs git.DeletePullRequestReviewerArgs) error {
- ret := _mock.Called(context1, deletePullRequestReviewerArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for DeletePullRequestReviewer")
- }
-
- var r0 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.DeletePullRequestReviewerArgs) error); ok {
- r0 = returnFunc(context1, deletePullRequestReviewerArgs)
- } else {
- r0 = ret.Error(0)
- }
- return r0
-}
-
-// Client_DeletePullRequestReviewer_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DeletePullRequestReviewer'
-type Client_DeletePullRequestReviewer_Call struct {
- *mock.Call
-}
-
-// DeletePullRequestReviewer is a helper method to define mock.On call
-// - context1
-// - deletePullRequestReviewerArgs
-func (_e *Client_Expecter) DeletePullRequestReviewer(context1 interface{}, deletePullRequestReviewerArgs interface{}) *Client_DeletePullRequestReviewer_Call {
- return &Client_DeletePullRequestReviewer_Call{Call: _e.mock.On("DeletePullRequestReviewer", context1, deletePullRequestReviewerArgs)}
-}
-
-func (_c *Client_DeletePullRequestReviewer_Call) Run(run func(context1 context.Context, deletePullRequestReviewerArgs git.DeletePullRequestReviewerArgs)) *Client_DeletePullRequestReviewer_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.DeletePullRequestReviewerArgs))
- })
- return _c
-}
-
-func (_c *Client_DeletePullRequestReviewer_Call) Return(err error) *Client_DeletePullRequestReviewer_Call {
- _c.Call.Return(err)
- return _c
-}
-
-func (_c *Client_DeletePullRequestReviewer_Call) RunAndReturn(run func(context1 context.Context, deletePullRequestReviewerArgs git.DeletePullRequestReviewerArgs) error) *Client_DeletePullRequestReviewer_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// DeletePullRequestStatus provides a mock function for the type Client
-func (_mock *Client) DeletePullRequestStatus(context1 context.Context, deletePullRequestStatusArgs git.DeletePullRequestStatusArgs) error {
- ret := _mock.Called(context1, deletePullRequestStatusArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for DeletePullRequestStatus")
- }
-
- var r0 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.DeletePullRequestStatusArgs) error); ok {
- r0 = returnFunc(context1, deletePullRequestStatusArgs)
- } else {
- r0 = ret.Error(0)
- }
- return r0
-}
-
-// Client_DeletePullRequestStatus_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DeletePullRequestStatus'
-type Client_DeletePullRequestStatus_Call struct {
- *mock.Call
-}
-
-// DeletePullRequestStatus is a helper method to define mock.On call
-// - context1
-// - deletePullRequestStatusArgs
-func (_e *Client_Expecter) DeletePullRequestStatus(context1 interface{}, deletePullRequestStatusArgs interface{}) *Client_DeletePullRequestStatus_Call {
- return &Client_DeletePullRequestStatus_Call{Call: _e.mock.On("DeletePullRequestStatus", context1, deletePullRequestStatusArgs)}
-}
-
-func (_c *Client_DeletePullRequestStatus_Call) Run(run func(context1 context.Context, deletePullRequestStatusArgs git.DeletePullRequestStatusArgs)) *Client_DeletePullRequestStatus_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.DeletePullRequestStatusArgs))
- })
- return _c
-}
-
-func (_c *Client_DeletePullRequestStatus_Call) Return(err error) *Client_DeletePullRequestStatus_Call {
- _c.Call.Return(err)
- return _c
-}
-
-func (_c *Client_DeletePullRequestStatus_Call) RunAndReturn(run func(context1 context.Context, deletePullRequestStatusArgs git.DeletePullRequestStatusArgs) error) *Client_DeletePullRequestStatus_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// DeleteRefFavorite provides a mock function for the type Client
-func (_mock *Client) DeleteRefFavorite(context1 context.Context, deleteRefFavoriteArgs git.DeleteRefFavoriteArgs) error {
- ret := _mock.Called(context1, deleteRefFavoriteArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for DeleteRefFavorite")
- }
-
- var r0 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.DeleteRefFavoriteArgs) error); ok {
- r0 = returnFunc(context1, deleteRefFavoriteArgs)
- } else {
- r0 = ret.Error(0)
- }
- return r0
-}
-
-// Client_DeleteRefFavorite_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DeleteRefFavorite'
-type Client_DeleteRefFavorite_Call struct {
- *mock.Call
-}
-
-// DeleteRefFavorite is a helper method to define mock.On call
-// - context1
-// - deleteRefFavoriteArgs
-func (_e *Client_Expecter) DeleteRefFavorite(context1 interface{}, deleteRefFavoriteArgs interface{}) *Client_DeleteRefFavorite_Call {
- return &Client_DeleteRefFavorite_Call{Call: _e.mock.On("DeleteRefFavorite", context1, deleteRefFavoriteArgs)}
-}
-
-func (_c *Client_DeleteRefFavorite_Call) Run(run func(context1 context.Context, deleteRefFavoriteArgs git.DeleteRefFavoriteArgs)) *Client_DeleteRefFavorite_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.DeleteRefFavoriteArgs))
- })
- return _c
-}
-
-func (_c *Client_DeleteRefFavorite_Call) Return(err error) *Client_DeleteRefFavorite_Call {
- _c.Call.Return(err)
- return _c
-}
-
-func (_c *Client_DeleteRefFavorite_Call) RunAndReturn(run func(context1 context.Context, deleteRefFavoriteArgs git.DeleteRefFavoriteArgs) error) *Client_DeleteRefFavorite_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// DeleteRepository provides a mock function for the type Client
-func (_mock *Client) DeleteRepository(context1 context.Context, deleteRepositoryArgs git.DeleteRepositoryArgs) error {
- ret := _mock.Called(context1, deleteRepositoryArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for DeleteRepository")
- }
-
- var r0 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.DeleteRepositoryArgs) error); ok {
- r0 = returnFunc(context1, deleteRepositoryArgs)
- } else {
- r0 = ret.Error(0)
- }
- return r0
-}
-
-// Client_DeleteRepository_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DeleteRepository'
-type Client_DeleteRepository_Call struct {
- *mock.Call
-}
-
-// DeleteRepository is a helper method to define mock.On call
-// - context1
-// - deleteRepositoryArgs
-func (_e *Client_Expecter) DeleteRepository(context1 interface{}, deleteRepositoryArgs interface{}) *Client_DeleteRepository_Call {
- return &Client_DeleteRepository_Call{Call: _e.mock.On("DeleteRepository", context1, deleteRepositoryArgs)}
-}
-
-func (_c *Client_DeleteRepository_Call) Run(run func(context1 context.Context, deleteRepositoryArgs git.DeleteRepositoryArgs)) *Client_DeleteRepository_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.DeleteRepositoryArgs))
- })
- return _c
-}
-
-func (_c *Client_DeleteRepository_Call) Return(err error) *Client_DeleteRepository_Call {
- _c.Call.Return(err)
- return _c
-}
-
-func (_c *Client_DeleteRepository_Call) RunAndReturn(run func(context1 context.Context, deleteRepositoryArgs git.DeleteRepositoryArgs) error) *Client_DeleteRepository_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// DeleteRepositoryFromRecycleBin provides a mock function for the type Client
-func (_mock *Client) DeleteRepositoryFromRecycleBin(context1 context.Context, deleteRepositoryFromRecycleBinArgs git.DeleteRepositoryFromRecycleBinArgs) error {
- ret := _mock.Called(context1, deleteRepositoryFromRecycleBinArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for DeleteRepositoryFromRecycleBin")
- }
-
- var r0 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.DeleteRepositoryFromRecycleBinArgs) error); ok {
- r0 = returnFunc(context1, deleteRepositoryFromRecycleBinArgs)
- } else {
- r0 = ret.Error(0)
- }
- return r0
-}
-
-// Client_DeleteRepositoryFromRecycleBin_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DeleteRepositoryFromRecycleBin'
-type Client_DeleteRepositoryFromRecycleBin_Call struct {
- *mock.Call
-}
-
-// DeleteRepositoryFromRecycleBin is a helper method to define mock.On call
-// - context1
-// - deleteRepositoryFromRecycleBinArgs
-func (_e *Client_Expecter) DeleteRepositoryFromRecycleBin(context1 interface{}, deleteRepositoryFromRecycleBinArgs interface{}) *Client_DeleteRepositoryFromRecycleBin_Call {
- return &Client_DeleteRepositoryFromRecycleBin_Call{Call: _e.mock.On("DeleteRepositoryFromRecycleBin", context1, deleteRepositoryFromRecycleBinArgs)}
-}
-
-func (_c *Client_DeleteRepositoryFromRecycleBin_Call) Run(run func(context1 context.Context, deleteRepositoryFromRecycleBinArgs git.DeleteRepositoryFromRecycleBinArgs)) *Client_DeleteRepositoryFromRecycleBin_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.DeleteRepositoryFromRecycleBinArgs))
- })
- return _c
-}
-
-func (_c *Client_DeleteRepositoryFromRecycleBin_Call) Return(err error) *Client_DeleteRepositoryFromRecycleBin_Call {
- _c.Call.Return(err)
- return _c
-}
-
-func (_c *Client_DeleteRepositoryFromRecycleBin_Call) RunAndReturn(run func(context1 context.Context, deleteRepositoryFromRecycleBinArgs git.DeleteRepositoryFromRecycleBinArgs) error) *Client_DeleteRepositoryFromRecycleBin_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetAnnotatedTag provides a mock function for the type Client
-func (_mock *Client) GetAnnotatedTag(context1 context.Context, getAnnotatedTagArgs git.GetAnnotatedTagArgs) (*git.GitAnnotatedTag, error) {
- ret := _mock.Called(context1, getAnnotatedTagArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetAnnotatedTag")
- }
-
- var r0 *git.GitAnnotatedTag
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetAnnotatedTagArgs) (*git.GitAnnotatedTag, error)); ok {
- return returnFunc(context1, getAnnotatedTagArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetAnnotatedTagArgs) *git.GitAnnotatedTag); ok {
- r0 = returnFunc(context1, getAnnotatedTagArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*git.GitAnnotatedTag)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetAnnotatedTagArgs) error); ok {
- r1 = returnFunc(context1, getAnnotatedTagArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetAnnotatedTag_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAnnotatedTag'
-type Client_GetAnnotatedTag_Call struct {
- *mock.Call
-}
-
-// GetAnnotatedTag is a helper method to define mock.On call
-// - context1
-// - getAnnotatedTagArgs
-func (_e *Client_Expecter) GetAnnotatedTag(context1 interface{}, getAnnotatedTagArgs interface{}) *Client_GetAnnotatedTag_Call {
- return &Client_GetAnnotatedTag_Call{Call: _e.mock.On("GetAnnotatedTag", context1, getAnnotatedTagArgs)}
-}
-
-func (_c *Client_GetAnnotatedTag_Call) Run(run func(context1 context.Context, getAnnotatedTagArgs git.GetAnnotatedTagArgs)) *Client_GetAnnotatedTag_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetAnnotatedTagArgs))
- })
- return _c
-}
-
-func (_c *Client_GetAnnotatedTag_Call) Return(gitAnnotatedTag *git.GitAnnotatedTag, err error) *Client_GetAnnotatedTag_Call {
- _c.Call.Return(gitAnnotatedTag, err)
- return _c
-}
-
-func (_c *Client_GetAnnotatedTag_Call) RunAndReturn(run func(context1 context.Context, getAnnotatedTagArgs git.GetAnnotatedTagArgs) (*git.GitAnnotatedTag, error)) *Client_GetAnnotatedTag_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetAttachmentContent provides a mock function for the type Client
-func (_mock *Client) GetAttachmentContent(context1 context.Context, getAttachmentContentArgs git.GetAttachmentContentArgs) (io.ReadCloser, error) {
- ret := _mock.Called(context1, getAttachmentContentArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetAttachmentContent")
- }
-
- var r0 io.ReadCloser
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetAttachmentContentArgs) (io.ReadCloser, error)); ok {
- return returnFunc(context1, getAttachmentContentArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetAttachmentContentArgs) io.ReadCloser); ok {
- r0 = returnFunc(context1, getAttachmentContentArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(io.ReadCloser)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetAttachmentContentArgs) error); ok {
- r1 = returnFunc(context1, getAttachmentContentArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetAttachmentContent_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAttachmentContent'
-type Client_GetAttachmentContent_Call struct {
- *mock.Call
-}
-
-// GetAttachmentContent is a helper method to define mock.On call
-// - context1
-// - getAttachmentContentArgs
-func (_e *Client_Expecter) GetAttachmentContent(context1 interface{}, getAttachmentContentArgs interface{}) *Client_GetAttachmentContent_Call {
- return &Client_GetAttachmentContent_Call{Call: _e.mock.On("GetAttachmentContent", context1, getAttachmentContentArgs)}
-}
-
-func (_c *Client_GetAttachmentContent_Call) Run(run func(context1 context.Context, getAttachmentContentArgs git.GetAttachmentContentArgs)) *Client_GetAttachmentContent_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetAttachmentContentArgs))
- })
- return _c
-}
-
-func (_c *Client_GetAttachmentContent_Call) Return(readCloser io.ReadCloser, err error) *Client_GetAttachmentContent_Call {
- _c.Call.Return(readCloser, err)
- return _c
-}
-
-func (_c *Client_GetAttachmentContent_Call) RunAndReturn(run func(context1 context.Context, getAttachmentContentArgs git.GetAttachmentContentArgs) (io.ReadCloser, error)) *Client_GetAttachmentContent_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetAttachmentZip provides a mock function for the type Client
-func (_mock *Client) GetAttachmentZip(context1 context.Context, getAttachmentZipArgs git.GetAttachmentZipArgs) (io.ReadCloser, error) {
- ret := _mock.Called(context1, getAttachmentZipArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetAttachmentZip")
- }
-
- var r0 io.ReadCloser
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetAttachmentZipArgs) (io.ReadCloser, error)); ok {
- return returnFunc(context1, getAttachmentZipArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetAttachmentZipArgs) io.ReadCloser); ok {
- r0 = returnFunc(context1, getAttachmentZipArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(io.ReadCloser)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetAttachmentZipArgs) error); ok {
- r1 = returnFunc(context1, getAttachmentZipArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetAttachmentZip_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAttachmentZip'
-type Client_GetAttachmentZip_Call struct {
- *mock.Call
-}
-
-// GetAttachmentZip is a helper method to define mock.On call
-// - context1
-// - getAttachmentZipArgs
-func (_e *Client_Expecter) GetAttachmentZip(context1 interface{}, getAttachmentZipArgs interface{}) *Client_GetAttachmentZip_Call {
- return &Client_GetAttachmentZip_Call{Call: _e.mock.On("GetAttachmentZip", context1, getAttachmentZipArgs)}
-}
-
-func (_c *Client_GetAttachmentZip_Call) Run(run func(context1 context.Context, getAttachmentZipArgs git.GetAttachmentZipArgs)) *Client_GetAttachmentZip_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetAttachmentZipArgs))
- })
- return _c
-}
-
-func (_c *Client_GetAttachmentZip_Call) Return(readCloser io.ReadCloser, err error) *Client_GetAttachmentZip_Call {
- _c.Call.Return(readCloser, err)
- return _c
-}
-
-func (_c *Client_GetAttachmentZip_Call) RunAndReturn(run func(context1 context.Context, getAttachmentZipArgs git.GetAttachmentZipArgs) (io.ReadCloser, error)) *Client_GetAttachmentZip_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetAttachments provides a mock function for the type Client
-func (_mock *Client) GetAttachments(context1 context.Context, getAttachmentsArgs git.GetAttachmentsArgs) (*[]git.Attachment, error) {
- ret := _mock.Called(context1, getAttachmentsArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetAttachments")
- }
-
- var r0 *[]git.Attachment
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetAttachmentsArgs) (*[]git.Attachment, error)); ok {
- return returnFunc(context1, getAttachmentsArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetAttachmentsArgs) *[]git.Attachment); ok {
- r0 = returnFunc(context1, getAttachmentsArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*[]git.Attachment)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetAttachmentsArgs) error); ok {
- r1 = returnFunc(context1, getAttachmentsArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetAttachments_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetAttachments'
-type Client_GetAttachments_Call struct {
- *mock.Call
-}
-
-// GetAttachments is a helper method to define mock.On call
-// - context1
-// - getAttachmentsArgs
-func (_e *Client_Expecter) GetAttachments(context1 interface{}, getAttachmentsArgs interface{}) *Client_GetAttachments_Call {
- return &Client_GetAttachments_Call{Call: _e.mock.On("GetAttachments", context1, getAttachmentsArgs)}
-}
-
-func (_c *Client_GetAttachments_Call) Run(run func(context1 context.Context, getAttachmentsArgs git.GetAttachmentsArgs)) *Client_GetAttachments_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetAttachmentsArgs))
- })
- return _c
-}
-
-func (_c *Client_GetAttachments_Call) Return(attachments *[]git.Attachment, err error) *Client_GetAttachments_Call {
- _c.Call.Return(attachments, err)
- return _c
-}
-
-func (_c *Client_GetAttachments_Call) RunAndReturn(run func(context1 context.Context, getAttachmentsArgs git.GetAttachmentsArgs) (*[]git.Attachment, error)) *Client_GetAttachments_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetBlob provides a mock function for the type Client
-func (_mock *Client) GetBlob(context1 context.Context, getBlobArgs git.GetBlobArgs) (*git.GitBlobRef, error) {
- ret := _mock.Called(context1, getBlobArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetBlob")
- }
-
- var r0 *git.GitBlobRef
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetBlobArgs) (*git.GitBlobRef, error)); ok {
- return returnFunc(context1, getBlobArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetBlobArgs) *git.GitBlobRef); ok {
- r0 = returnFunc(context1, getBlobArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*git.GitBlobRef)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetBlobArgs) error); ok {
- r1 = returnFunc(context1, getBlobArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetBlob_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetBlob'
-type Client_GetBlob_Call struct {
- *mock.Call
-}
-
-// GetBlob is a helper method to define mock.On call
-// - context1
-// - getBlobArgs
-func (_e *Client_Expecter) GetBlob(context1 interface{}, getBlobArgs interface{}) *Client_GetBlob_Call {
- return &Client_GetBlob_Call{Call: _e.mock.On("GetBlob", context1, getBlobArgs)}
-}
-
-func (_c *Client_GetBlob_Call) Run(run func(context1 context.Context, getBlobArgs git.GetBlobArgs)) *Client_GetBlob_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetBlobArgs))
- })
- return _c
-}
-
-func (_c *Client_GetBlob_Call) Return(gitBlobRef *git.GitBlobRef, err error) *Client_GetBlob_Call {
- _c.Call.Return(gitBlobRef, err)
- return _c
-}
-
-func (_c *Client_GetBlob_Call) RunAndReturn(run func(context1 context.Context, getBlobArgs git.GetBlobArgs) (*git.GitBlobRef, error)) *Client_GetBlob_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetBlobContent provides a mock function for the type Client
-func (_mock *Client) GetBlobContent(context1 context.Context, getBlobContentArgs git.GetBlobContentArgs) (io.ReadCloser, error) {
- ret := _mock.Called(context1, getBlobContentArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetBlobContent")
- }
-
- var r0 io.ReadCloser
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetBlobContentArgs) (io.ReadCloser, error)); ok {
- return returnFunc(context1, getBlobContentArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetBlobContentArgs) io.ReadCloser); ok {
- r0 = returnFunc(context1, getBlobContentArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(io.ReadCloser)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetBlobContentArgs) error); ok {
- r1 = returnFunc(context1, getBlobContentArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetBlobContent_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetBlobContent'
-type Client_GetBlobContent_Call struct {
- *mock.Call
-}
-
-// GetBlobContent is a helper method to define mock.On call
-// - context1
-// - getBlobContentArgs
-func (_e *Client_Expecter) GetBlobContent(context1 interface{}, getBlobContentArgs interface{}) *Client_GetBlobContent_Call {
- return &Client_GetBlobContent_Call{Call: _e.mock.On("GetBlobContent", context1, getBlobContentArgs)}
-}
-
-func (_c *Client_GetBlobContent_Call) Run(run func(context1 context.Context, getBlobContentArgs git.GetBlobContentArgs)) *Client_GetBlobContent_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetBlobContentArgs))
- })
- return _c
-}
-
-func (_c *Client_GetBlobContent_Call) Return(readCloser io.ReadCloser, err error) *Client_GetBlobContent_Call {
- _c.Call.Return(readCloser, err)
- return _c
-}
-
-func (_c *Client_GetBlobContent_Call) RunAndReturn(run func(context1 context.Context, getBlobContentArgs git.GetBlobContentArgs) (io.ReadCloser, error)) *Client_GetBlobContent_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetBlobZip provides a mock function for the type Client
-func (_mock *Client) GetBlobZip(context1 context.Context, getBlobZipArgs git.GetBlobZipArgs) (io.ReadCloser, error) {
- ret := _mock.Called(context1, getBlobZipArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetBlobZip")
- }
-
- var r0 io.ReadCloser
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetBlobZipArgs) (io.ReadCloser, error)); ok {
- return returnFunc(context1, getBlobZipArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetBlobZipArgs) io.ReadCloser); ok {
- r0 = returnFunc(context1, getBlobZipArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(io.ReadCloser)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetBlobZipArgs) error); ok {
- r1 = returnFunc(context1, getBlobZipArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetBlobZip_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetBlobZip'
-type Client_GetBlobZip_Call struct {
- *mock.Call
-}
-
-// GetBlobZip is a helper method to define mock.On call
-// - context1
-// - getBlobZipArgs
-func (_e *Client_Expecter) GetBlobZip(context1 interface{}, getBlobZipArgs interface{}) *Client_GetBlobZip_Call {
- return &Client_GetBlobZip_Call{Call: _e.mock.On("GetBlobZip", context1, getBlobZipArgs)}
-}
-
-func (_c *Client_GetBlobZip_Call) Run(run func(context1 context.Context, getBlobZipArgs git.GetBlobZipArgs)) *Client_GetBlobZip_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetBlobZipArgs))
- })
- return _c
-}
-
-func (_c *Client_GetBlobZip_Call) Return(readCloser io.ReadCloser, err error) *Client_GetBlobZip_Call {
- _c.Call.Return(readCloser, err)
- return _c
-}
-
-func (_c *Client_GetBlobZip_Call) RunAndReturn(run func(context1 context.Context, getBlobZipArgs git.GetBlobZipArgs) (io.ReadCloser, error)) *Client_GetBlobZip_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetBlobsZip provides a mock function for the type Client
-func (_mock *Client) GetBlobsZip(context1 context.Context, getBlobsZipArgs git.GetBlobsZipArgs) (io.ReadCloser, error) {
- ret := _mock.Called(context1, getBlobsZipArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetBlobsZip")
- }
-
- var r0 io.ReadCloser
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetBlobsZipArgs) (io.ReadCloser, error)); ok {
- return returnFunc(context1, getBlobsZipArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetBlobsZipArgs) io.ReadCloser); ok {
- r0 = returnFunc(context1, getBlobsZipArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(io.ReadCloser)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetBlobsZipArgs) error); ok {
- r1 = returnFunc(context1, getBlobsZipArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetBlobsZip_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetBlobsZip'
-type Client_GetBlobsZip_Call struct {
- *mock.Call
-}
-
-// GetBlobsZip is a helper method to define mock.On call
-// - context1
-// - getBlobsZipArgs
-func (_e *Client_Expecter) GetBlobsZip(context1 interface{}, getBlobsZipArgs interface{}) *Client_GetBlobsZip_Call {
- return &Client_GetBlobsZip_Call{Call: _e.mock.On("GetBlobsZip", context1, getBlobsZipArgs)}
-}
-
-func (_c *Client_GetBlobsZip_Call) Run(run func(context1 context.Context, getBlobsZipArgs git.GetBlobsZipArgs)) *Client_GetBlobsZip_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetBlobsZipArgs))
- })
- return _c
-}
-
-func (_c *Client_GetBlobsZip_Call) Return(readCloser io.ReadCloser, err error) *Client_GetBlobsZip_Call {
- _c.Call.Return(readCloser, err)
- return _c
-}
-
-func (_c *Client_GetBlobsZip_Call) RunAndReturn(run func(context1 context.Context, getBlobsZipArgs git.GetBlobsZipArgs) (io.ReadCloser, error)) *Client_GetBlobsZip_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetBranch provides a mock function for the type Client
-func (_mock *Client) GetBranch(context1 context.Context, getBranchArgs git.GetBranchArgs) (*git.GitBranchStats, error) {
- ret := _mock.Called(context1, getBranchArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetBranch")
- }
-
- var r0 *git.GitBranchStats
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetBranchArgs) (*git.GitBranchStats, error)); ok {
- return returnFunc(context1, getBranchArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetBranchArgs) *git.GitBranchStats); ok {
- r0 = returnFunc(context1, getBranchArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*git.GitBranchStats)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetBranchArgs) error); ok {
- r1 = returnFunc(context1, getBranchArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetBranch_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetBranch'
-type Client_GetBranch_Call struct {
- *mock.Call
-}
-
-// GetBranch is a helper method to define mock.On call
-// - context1
-// - getBranchArgs
-func (_e *Client_Expecter) GetBranch(context1 interface{}, getBranchArgs interface{}) *Client_GetBranch_Call {
- return &Client_GetBranch_Call{Call: _e.mock.On("GetBranch", context1, getBranchArgs)}
-}
-
-func (_c *Client_GetBranch_Call) Run(run func(context1 context.Context, getBranchArgs git.GetBranchArgs)) *Client_GetBranch_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetBranchArgs))
- })
- return _c
-}
-
-func (_c *Client_GetBranch_Call) Return(gitBranchStats *git.GitBranchStats, err error) *Client_GetBranch_Call {
- _c.Call.Return(gitBranchStats, err)
- return _c
-}
-
-func (_c *Client_GetBranch_Call) RunAndReturn(run func(context1 context.Context, getBranchArgs git.GetBranchArgs) (*git.GitBranchStats, error)) *Client_GetBranch_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetBranches provides a mock function for the type Client
-func (_mock *Client) GetBranches(context1 context.Context, getBranchesArgs git.GetBranchesArgs) (*[]git.GitBranchStats, error) {
- ret := _mock.Called(context1, getBranchesArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetBranches")
- }
-
- var r0 *[]git.GitBranchStats
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetBranchesArgs) (*[]git.GitBranchStats, error)); ok {
- return returnFunc(context1, getBranchesArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetBranchesArgs) *[]git.GitBranchStats); ok {
- r0 = returnFunc(context1, getBranchesArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*[]git.GitBranchStats)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetBranchesArgs) error); ok {
- r1 = returnFunc(context1, getBranchesArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetBranches_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetBranches'
-type Client_GetBranches_Call struct {
- *mock.Call
-}
-
-// GetBranches is a helper method to define mock.On call
-// - context1
-// - getBranchesArgs
-func (_e *Client_Expecter) GetBranches(context1 interface{}, getBranchesArgs interface{}) *Client_GetBranches_Call {
- return &Client_GetBranches_Call{Call: _e.mock.On("GetBranches", context1, getBranchesArgs)}
-}
-
-func (_c *Client_GetBranches_Call) Run(run func(context1 context.Context, getBranchesArgs git.GetBranchesArgs)) *Client_GetBranches_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetBranchesArgs))
- })
- return _c
-}
-
-func (_c *Client_GetBranches_Call) Return(gitBranchStatss *[]git.GitBranchStats, err error) *Client_GetBranches_Call {
- _c.Call.Return(gitBranchStatss, err)
- return _c
-}
-
-func (_c *Client_GetBranches_Call) RunAndReturn(run func(context1 context.Context, getBranchesArgs git.GetBranchesArgs) (*[]git.GitBranchStats, error)) *Client_GetBranches_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetChanges provides a mock function for the type Client
-func (_mock *Client) GetChanges(context1 context.Context, getChangesArgs git.GetChangesArgs) (*git.GitCommitChanges, error) {
- ret := _mock.Called(context1, getChangesArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetChanges")
- }
-
- var r0 *git.GitCommitChanges
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetChangesArgs) (*git.GitCommitChanges, error)); ok {
- return returnFunc(context1, getChangesArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetChangesArgs) *git.GitCommitChanges); ok {
- r0 = returnFunc(context1, getChangesArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*git.GitCommitChanges)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetChangesArgs) error); ok {
- r1 = returnFunc(context1, getChangesArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetChanges_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetChanges'
-type Client_GetChanges_Call struct {
- *mock.Call
-}
-
-// GetChanges is a helper method to define mock.On call
-// - context1
-// - getChangesArgs
-func (_e *Client_Expecter) GetChanges(context1 interface{}, getChangesArgs interface{}) *Client_GetChanges_Call {
- return &Client_GetChanges_Call{Call: _e.mock.On("GetChanges", context1, getChangesArgs)}
-}
-
-func (_c *Client_GetChanges_Call) Run(run func(context1 context.Context, getChangesArgs git.GetChangesArgs)) *Client_GetChanges_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetChangesArgs))
- })
- return _c
-}
-
-func (_c *Client_GetChanges_Call) Return(gitCommitChanges *git.GitCommitChanges, err error) *Client_GetChanges_Call {
- _c.Call.Return(gitCommitChanges, err)
- return _c
-}
-
-func (_c *Client_GetChanges_Call) RunAndReturn(run func(context1 context.Context, getChangesArgs git.GetChangesArgs) (*git.GitCommitChanges, error)) *Client_GetChanges_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetCherryPick provides a mock function for the type Client
-func (_mock *Client) GetCherryPick(context1 context.Context, getCherryPickArgs git.GetCherryPickArgs) (*git.GitCherryPick, error) {
- ret := _mock.Called(context1, getCherryPickArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetCherryPick")
- }
-
- var r0 *git.GitCherryPick
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetCherryPickArgs) (*git.GitCherryPick, error)); ok {
- return returnFunc(context1, getCherryPickArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetCherryPickArgs) *git.GitCherryPick); ok {
- r0 = returnFunc(context1, getCherryPickArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*git.GitCherryPick)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetCherryPickArgs) error); ok {
- r1 = returnFunc(context1, getCherryPickArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetCherryPick_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetCherryPick'
-type Client_GetCherryPick_Call struct {
- *mock.Call
-}
-
-// GetCherryPick is a helper method to define mock.On call
-// - context1
-// - getCherryPickArgs
-func (_e *Client_Expecter) GetCherryPick(context1 interface{}, getCherryPickArgs interface{}) *Client_GetCherryPick_Call {
- return &Client_GetCherryPick_Call{Call: _e.mock.On("GetCherryPick", context1, getCherryPickArgs)}
-}
-
-func (_c *Client_GetCherryPick_Call) Run(run func(context1 context.Context, getCherryPickArgs git.GetCherryPickArgs)) *Client_GetCherryPick_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetCherryPickArgs))
- })
- return _c
-}
-
-func (_c *Client_GetCherryPick_Call) Return(gitCherryPick *git.GitCherryPick, err error) *Client_GetCherryPick_Call {
- _c.Call.Return(gitCherryPick, err)
- return _c
-}
-
-func (_c *Client_GetCherryPick_Call) RunAndReturn(run func(context1 context.Context, getCherryPickArgs git.GetCherryPickArgs) (*git.GitCherryPick, error)) *Client_GetCherryPick_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetCherryPickForRefName provides a mock function for the type Client
-func (_mock *Client) GetCherryPickForRefName(context1 context.Context, getCherryPickForRefNameArgs git.GetCherryPickForRefNameArgs) (*git.GitCherryPick, error) {
- ret := _mock.Called(context1, getCherryPickForRefNameArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetCherryPickForRefName")
- }
-
- var r0 *git.GitCherryPick
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetCherryPickForRefNameArgs) (*git.GitCherryPick, error)); ok {
- return returnFunc(context1, getCherryPickForRefNameArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetCherryPickForRefNameArgs) *git.GitCherryPick); ok {
- r0 = returnFunc(context1, getCherryPickForRefNameArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*git.GitCherryPick)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetCherryPickForRefNameArgs) error); ok {
- r1 = returnFunc(context1, getCherryPickForRefNameArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetCherryPickForRefName_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetCherryPickForRefName'
-type Client_GetCherryPickForRefName_Call struct {
- *mock.Call
-}
-
-// GetCherryPickForRefName is a helper method to define mock.On call
-// - context1
-// - getCherryPickForRefNameArgs
-func (_e *Client_Expecter) GetCherryPickForRefName(context1 interface{}, getCherryPickForRefNameArgs interface{}) *Client_GetCherryPickForRefName_Call {
- return &Client_GetCherryPickForRefName_Call{Call: _e.mock.On("GetCherryPickForRefName", context1, getCherryPickForRefNameArgs)}
-}
-
-func (_c *Client_GetCherryPickForRefName_Call) Run(run func(context1 context.Context, getCherryPickForRefNameArgs git.GetCherryPickForRefNameArgs)) *Client_GetCherryPickForRefName_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetCherryPickForRefNameArgs))
- })
- return _c
-}
-
-func (_c *Client_GetCherryPickForRefName_Call) Return(gitCherryPick *git.GitCherryPick, err error) *Client_GetCherryPickForRefName_Call {
- _c.Call.Return(gitCherryPick, err)
- return _c
-}
-
-func (_c *Client_GetCherryPickForRefName_Call) RunAndReturn(run func(context1 context.Context, getCherryPickForRefNameArgs git.GetCherryPickForRefNameArgs) (*git.GitCherryPick, error)) *Client_GetCherryPickForRefName_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetComment provides a mock function for the type Client
-func (_mock *Client) GetComment(context1 context.Context, getCommentArgs git.GetCommentArgs) (*git.Comment, error) {
- ret := _mock.Called(context1, getCommentArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetComment")
- }
-
- var r0 *git.Comment
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetCommentArgs) (*git.Comment, error)); ok {
- return returnFunc(context1, getCommentArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetCommentArgs) *git.Comment); ok {
- r0 = returnFunc(context1, getCommentArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*git.Comment)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetCommentArgs) error); ok {
- r1 = returnFunc(context1, getCommentArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetComment_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetComment'
-type Client_GetComment_Call struct {
- *mock.Call
-}
-
-// GetComment is a helper method to define mock.On call
-// - context1
-// - getCommentArgs
-func (_e *Client_Expecter) GetComment(context1 interface{}, getCommentArgs interface{}) *Client_GetComment_Call {
- return &Client_GetComment_Call{Call: _e.mock.On("GetComment", context1, getCommentArgs)}
-}
-
-func (_c *Client_GetComment_Call) Run(run func(context1 context.Context, getCommentArgs git.GetCommentArgs)) *Client_GetComment_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetCommentArgs))
- })
- return _c
-}
-
-func (_c *Client_GetComment_Call) Return(comment *git.Comment, err error) *Client_GetComment_Call {
- _c.Call.Return(comment, err)
- return _c
-}
-
-func (_c *Client_GetComment_Call) RunAndReturn(run func(context1 context.Context, getCommentArgs git.GetCommentArgs) (*git.Comment, error)) *Client_GetComment_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetComments provides a mock function for the type Client
-func (_mock *Client) GetComments(context1 context.Context, getCommentsArgs git.GetCommentsArgs) (*[]git.Comment, error) {
- ret := _mock.Called(context1, getCommentsArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetComments")
- }
-
- var r0 *[]git.Comment
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetCommentsArgs) (*[]git.Comment, error)); ok {
- return returnFunc(context1, getCommentsArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetCommentsArgs) *[]git.Comment); ok {
- r0 = returnFunc(context1, getCommentsArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*[]git.Comment)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetCommentsArgs) error); ok {
- r1 = returnFunc(context1, getCommentsArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetComments_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetComments'
-type Client_GetComments_Call struct {
- *mock.Call
-}
-
-// GetComments is a helper method to define mock.On call
-// - context1
-// - getCommentsArgs
-func (_e *Client_Expecter) GetComments(context1 interface{}, getCommentsArgs interface{}) *Client_GetComments_Call {
- return &Client_GetComments_Call{Call: _e.mock.On("GetComments", context1, getCommentsArgs)}
-}
-
-func (_c *Client_GetComments_Call) Run(run func(context1 context.Context, getCommentsArgs git.GetCommentsArgs)) *Client_GetComments_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetCommentsArgs))
- })
- return _c
-}
-
-func (_c *Client_GetComments_Call) Return(comments *[]git.Comment, err error) *Client_GetComments_Call {
- _c.Call.Return(comments, err)
- return _c
-}
-
-func (_c *Client_GetComments_Call) RunAndReturn(run func(context1 context.Context, getCommentsArgs git.GetCommentsArgs) (*[]git.Comment, error)) *Client_GetComments_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetCommit provides a mock function for the type Client
-func (_mock *Client) GetCommit(context1 context.Context, getCommitArgs git.GetCommitArgs) (*git.GitCommit, error) {
- ret := _mock.Called(context1, getCommitArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetCommit")
- }
-
- var r0 *git.GitCommit
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetCommitArgs) (*git.GitCommit, error)); ok {
- return returnFunc(context1, getCommitArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetCommitArgs) *git.GitCommit); ok {
- r0 = returnFunc(context1, getCommitArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*git.GitCommit)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetCommitArgs) error); ok {
- r1 = returnFunc(context1, getCommitArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetCommit_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetCommit'
-type Client_GetCommit_Call struct {
- *mock.Call
-}
-
-// GetCommit is a helper method to define mock.On call
-// - context1
-// - getCommitArgs
-func (_e *Client_Expecter) GetCommit(context1 interface{}, getCommitArgs interface{}) *Client_GetCommit_Call {
- return &Client_GetCommit_Call{Call: _e.mock.On("GetCommit", context1, getCommitArgs)}
-}
-
-func (_c *Client_GetCommit_Call) Run(run func(context1 context.Context, getCommitArgs git.GetCommitArgs)) *Client_GetCommit_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetCommitArgs))
- })
- return _c
-}
-
-func (_c *Client_GetCommit_Call) Return(gitCommit *git.GitCommit, err error) *Client_GetCommit_Call {
- _c.Call.Return(gitCommit, err)
- return _c
-}
-
-func (_c *Client_GetCommit_Call) RunAndReturn(run func(context1 context.Context, getCommitArgs git.GetCommitArgs) (*git.GitCommit, error)) *Client_GetCommit_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetCommitDiffs provides a mock function for the type Client
-func (_mock *Client) GetCommitDiffs(context1 context.Context, getCommitDiffsArgs git.GetCommitDiffsArgs) (*git.GitCommitDiffs, error) {
- ret := _mock.Called(context1, getCommitDiffsArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetCommitDiffs")
- }
-
- var r0 *git.GitCommitDiffs
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetCommitDiffsArgs) (*git.GitCommitDiffs, error)); ok {
- return returnFunc(context1, getCommitDiffsArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetCommitDiffsArgs) *git.GitCommitDiffs); ok {
- r0 = returnFunc(context1, getCommitDiffsArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*git.GitCommitDiffs)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetCommitDiffsArgs) error); ok {
- r1 = returnFunc(context1, getCommitDiffsArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetCommitDiffs_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetCommitDiffs'
-type Client_GetCommitDiffs_Call struct {
- *mock.Call
-}
-
-// GetCommitDiffs is a helper method to define mock.On call
-// - context1
-// - getCommitDiffsArgs
-func (_e *Client_Expecter) GetCommitDiffs(context1 interface{}, getCommitDiffsArgs interface{}) *Client_GetCommitDiffs_Call {
- return &Client_GetCommitDiffs_Call{Call: _e.mock.On("GetCommitDiffs", context1, getCommitDiffsArgs)}
-}
-
-func (_c *Client_GetCommitDiffs_Call) Run(run func(context1 context.Context, getCommitDiffsArgs git.GetCommitDiffsArgs)) *Client_GetCommitDiffs_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetCommitDiffsArgs))
- })
- return _c
-}
-
-func (_c *Client_GetCommitDiffs_Call) Return(gitCommitDiffs *git.GitCommitDiffs, err error) *Client_GetCommitDiffs_Call {
- _c.Call.Return(gitCommitDiffs, err)
- return _c
-}
-
-func (_c *Client_GetCommitDiffs_Call) RunAndReturn(run func(context1 context.Context, getCommitDiffsArgs git.GetCommitDiffsArgs) (*git.GitCommitDiffs, error)) *Client_GetCommitDiffs_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetCommits provides a mock function for the type Client
-func (_mock *Client) GetCommits(context1 context.Context, getCommitsArgs git.GetCommitsArgs) (*[]git.GitCommitRef, error) {
- ret := _mock.Called(context1, getCommitsArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetCommits")
- }
-
- var r0 *[]git.GitCommitRef
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetCommitsArgs) (*[]git.GitCommitRef, error)); ok {
- return returnFunc(context1, getCommitsArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetCommitsArgs) *[]git.GitCommitRef); ok {
- r0 = returnFunc(context1, getCommitsArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*[]git.GitCommitRef)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetCommitsArgs) error); ok {
- r1 = returnFunc(context1, getCommitsArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetCommits_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetCommits'
-type Client_GetCommits_Call struct {
- *mock.Call
-}
-
-// GetCommits is a helper method to define mock.On call
-// - context1
-// - getCommitsArgs
-func (_e *Client_Expecter) GetCommits(context1 interface{}, getCommitsArgs interface{}) *Client_GetCommits_Call {
- return &Client_GetCommits_Call{Call: _e.mock.On("GetCommits", context1, getCommitsArgs)}
-}
-
-func (_c *Client_GetCommits_Call) Run(run func(context1 context.Context, getCommitsArgs git.GetCommitsArgs)) *Client_GetCommits_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetCommitsArgs))
- })
- return _c
-}
-
-func (_c *Client_GetCommits_Call) Return(gitCommitRefs *[]git.GitCommitRef, err error) *Client_GetCommits_Call {
- _c.Call.Return(gitCommitRefs, err)
- return _c
-}
-
-func (_c *Client_GetCommits_Call) RunAndReturn(run func(context1 context.Context, getCommitsArgs git.GetCommitsArgs) (*[]git.GitCommitRef, error)) *Client_GetCommits_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetCommitsBatch provides a mock function for the type Client
-func (_mock *Client) GetCommitsBatch(context1 context.Context, getCommitsBatchArgs git.GetCommitsBatchArgs) (*[]git.GitCommitRef, error) {
- ret := _mock.Called(context1, getCommitsBatchArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetCommitsBatch")
- }
-
- var r0 *[]git.GitCommitRef
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetCommitsBatchArgs) (*[]git.GitCommitRef, error)); ok {
- return returnFunc(context1, getCommitsBatchArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetCommitsBatchArgs) *[]git.GitCommitRef); ok {
- r0 = returnFunc(context1, getCommitsBatchArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*[]git.GitCommitRef)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetCommitsBatchArgs) error); ok {
- r1 = returnFunc(context1, getCommitsBatchArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetCommitsBatch_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetCommitsBatch'
-type Client_GetCommitsBatch_Call struct {
- *mock.Call
-}
-
-// GetCommitsBatch is a helper method to define mock.On call
-// - context1
-// - getCommitsBatchArgs
-func (_e *Client_Expecter) GetCommitsBatch(context1 interface{}, getCommitsBatchArgs interface{}) *Client_GetCommitsBatch_Call {
- return &Client_GetCommitsBatch_Call{Call: _e.mock.On("GetCommitsBatch", context1, getCommitsBatchArgs)}
-}
-
-func (_c *Client_GetCommitsBatch_Call) Run(run func(context1 context.Context, getCommitsBatchArgs git.GetCommitsBatchArgs)) *Client_GetCommitsBatch_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetCommitsBatchArgs))
- })
- return _c
-}
-
-func (_c *Client_GetCommitsBatch_Call) Return(gitCommitRefs *[]git.GitCommitRef, err error) *Client_GetCommitsBatch_Call {
- _c.Call.Return(gitCommitRefs, err)
- return _c
-}
-
-func (_c *Client_GetCommitsBatch_Call) RunAndReturn(run func(context1 context.Context, getCommitsBatchArgs git.GetCommitsBatchArgs) (*[]git.GitCommitRef, error)) *Client_GetCommitsBatch_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetDeletedRepositories provides a mock function for the type Client
-func (_mock *Client) GetDeletedRepositories(context1 context.Context, getDeletedRepositoriesArgs git.GetDeletedRepositoriesArgs) (*[]git.GitDeletedRepository, error) {
- ret := _mock.Called(context1, getDeletedRepositoriesArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetDeletedRepositories")
- }
-
- var r0 *[]git.GitDeletedRepository
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetDeletedRepositoriesArgs) (*[]git.GitDeletedRepository, error)); ok {
- return returnFunc(context1, getDeletedRepositoriesArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetDeletedRepositoriesArgs) *[]git.GitDeletedRepository); ok {
- r0 = returnFunc(context1, getDeletedRepositoriesArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*[]git.GitDeletedRepository)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetDeletedRepositoriesArgs) error); ok {
- r1 = returnFunc(context1, getDeletedRepositoriesArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetDeletedRepositories_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetDeletedRepositories'
-type Client_GetDeletedRepositories_Call struct {
- *mock.Call
-}
-
-// GetDeletedRepositories is a helper method to define mock.On call
-// - context1
-// - getDeletedRepositoriesArgs
-func (_e *Client_Expecter) GetDeletedRepositories(context1 interface{}, getDeletedRepositoriesArgs interface{}) *Client_GetDeletedRepositories_Call {
- return &Client_GetDeletedRepositories_Call{Call: _e.mock.On("GetDeletedRepositories", context1, getDeletedRepositoriesArgs)}
-}
-
-func (_c *Client_GetDeletedRepositories_Call) Run(run func(context1 context.Context, getDeletedRepositoriesArgs git.GetDeletedRepositoriesArgs)) *Client_GetDeletedRepositories_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetDeletedRepositoriesArgs))
- })
- return _c
-}
-
-func (_c *Client_GetDeletedRepositories_Call) Return(gitDeletedRepositorys *[]git.GitDeletedRepository, err error) *Client_GetDeletedRepositories_Call {
- _c.Call.Return(gitDeletedRepositorys, err)
- return _c
-}
-
-func (_c *Client_GetDeletedRepositories_Call) RunAndReturn(run func(context1 context.Context, getDeletedRepositoriesArgs git.GetDeletedRepositoriesArgs) (*[]git.GitDeletedRepository, error)) *Client_GetDeletedRepositories_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetForkSyncRequest provides a mock function for the type Client
-func (_mock *Client) GetForkSyncRequest(context1 context.Context, getForkSyncRequestArgs git.GetForkSyncRequestArgs) (*git.GitForkSyncRequest, error) {
- ret := _mock.Called(context1, getForkSyncRequestArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetForkSyncRequest")
- }
-
- var r0 *git.GitForkSyncRequest
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetForkSyncRequestArgs) (*git.GitForkSyncRequest, error)); ok {
- return returnFunc(context1, getForkSyncRequestArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetForkSyncRequestArgs) *git.GitForkSyncRequest); ok {
- r0 = returnFunc(context1, getForkSyncRequestArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*git.GitForkSyncRequest)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetForkSyncRequestArgs) error); ok {
- r1 = returnFunc(context1, getForkSyncRequestArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetForkSyncRequest_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetForkSyncRequest'
-type Client_GetForkSyncRequest_Call struct {
- *mock.Call
-}
-
-// GetForkSyncRequest is a helper method to define mock.On call
-// - context1
-// - getForkSyncRequestArgs
-func (_e *Client_Expecter) GetForkSyncRequest(context1 interface{}, getForkSyncRequestArgs interface{}) *Client_GetForkSyncRequest_Call {
- return &Client_GetForkSyncRequest_Call{Call: _e.mock.On("GetForkSyncRequest", context1, getForkSyncRequestArgs)}
-}
-
-func (_c *Client_GetForkSyncRequest_Call) Run(run func(context1 context.Context, getForkSyncRequestArgs git.GetForkSyncRequestArgs)) *Client_GetForkSyncRequest_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetForkSyncRequestArgs))
- })
- return _c
-}
-
-func (_c *Client_GetForkSyncRequest_Call) Return(gitForkSyncRequest *git.GitForkSyncRequest, err error) *Client_GetForkSyncRequest_Call {
- _c.Call.Return(gitForkSyncRequest, err)
- return _c
-}
-
-func (_c *Client_GetForkSyncRequest_Call) RunAndReturn(run func(context1 context.Context, getForkSyncRequestArgs git.GetForkSyncRequestArgs) (*git.GitForkSyncRequest, error)) *Client_GetForkSyncRequest_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetForkSyncRequests provides a mock function for the type Client
-func (_mock *Client) GetForkSyncRequests(context1 context.Context, getForkSyncRequestsArgs git.GetForkSyncRequestsArgs) (*[]git.GitForkSyncRequest, error) {
- ret := _mock.Called(context1, getForkSyncRequestsArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetForkSyncRequests")
- }
-
- var r0 *[]git.GitForkSyncRequest
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetForkSyncRequestsArgs) (*[]git.GitForkSyncRequest, error)); ok {
- return returnFunc(context1, getForkSyncRequestsArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetForkSyncRequestsArgs) *[]git.GitForkSyncRequest); ok {
- r0 = returnFunc(context1, getForkSyncRequestsArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*[]git.GitForkSyncRequest)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetForkSyncRequestsArgs) error); ok {
- r1 = returnFunc(context1, getForkSyncRequestsArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetForkSyncRequests_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetForkSyncRequests'
-type Client_GetForkSyncRequests_Call struct {
- *mock.Call
-}
-
-// GetForkSyncRequests is a helper method to define mock.On call
-// - context1
-// - getForkSyncRequestsArgs
-func (_e *Client_Expecter) GetForkSyncRequests(context1 interface{}, getForkSyncRequestsArgs interface{}) *Client_GetForkSyncRequests_Call {
- return &Client_GetForkSyncRequests_Call{Call: _e.mock.On("GetForkSyncRequests", context1, getForkSyncRequestsArgs)}
-}
-
-func (_c *Client_GetForkSyncRequests_Call) Run(run func(context1 context.Context, getForkSyncRequestsArgs git.GetForkSyncRequestsArgs)) *Client_GetForkSyncRequests_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetForkSyncRequestsArgs))
- })
- return _c
-}
-
-func (_c *Client_GetForkSyncRequests_Call) Return(gitForkSyncRequests *[]git.GitForkSyncRequest, err error) *Client_GetForkSyncRequests_Call {
- _c.Call.Return(gitForkSyncRequests, err)
- return _c
-}
-
-func (_c *Client_GetForkSyncRequests_Call) RunAndReturn(run func(context1 context.Context, getForkSyncRequestsArgs git.GetForkSyncRequestsArgs) (*[]git.GitForkSyncRequest, error)) *Client_GetForkSyncRequests_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetForks provides a mock function for the type Client
-func (_mock *Client) GetForks(context1 context.Context, getForksArgs git.GetForksArgs) (*[]git.GitRepositoryRef, error) {
- ret := _mock.Called(context1, getForksArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetForks")
- }
-
- var r0 *[]git.GitRepositoryRef
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetForksArgs) (*[]git.GitRepositoryRef, error)); ok {
- return returnFunc(context1, getForksArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetForksArgs) *[]git.GitRepositoryRef); ok {
- r0 = returnFunc(context1, getForksArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*[]git.GitRepositoryRef)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetForksArgs) error); ok {
- r1 = returnFunc(context1, getForksArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetForks_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetForks'
-type Client_GetForks_Call struct {
- *mock.Call
-}
-
-// GetForks is a helper method to define mock.On call
-// - context1
-// - getForksArgs
-func (_e *Client_Expecter) GetForks(context1 interface{}, getForksArgs interface{}) *Client_GetForks_Call {
- return &Client_GetForks_Call{Call: _e.mock.On("GetForks", context1, getForksArgs)}
-}
-
-func (_c *Client_GetForks_Call) Run(run func(context1 context.Context, getForksArgs git.GetForksArgs)) *Client_GetForks_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetForksArgs))
- })
- return _c
-}
-
-func (_c *Client_GetForks_Call) Return(gitRepositoryRefs *[]git.GitRepositoryRef, err error) *Client_GetForks_Call {
- _c.Call.Return(gitRepositoryRefs, err)
- return _c
-}
-
-func (_c *Client_GetForks_Call) RunAndReturn(run func(context1 context.Context, getForksArgs git.GetForksArgs) (*[]git.GitRepositoryRef, error)) *Client_GetForks_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetImportRequest provides a mock function for the type Client
-func (_mock *Client) GetImportRequest(context1 context.Context, getImportRequestArgs git.GetImportRequestArgs) (*git.GitImportRequest, error) {
- ret := _mock.Called(context1, getImportRequestArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetImportRequest")
- }
-
- var r0 *git.GitImportRequest
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetImportRequestArgs) (*git.GitImportRequest, error)); ok {
- return returnFunc(context1, getImportRequestArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetImportRequestArgs) *git.GitImportRequest); ok {
- r0 = returnFunc(context1, getImportRequestArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*git.GitImportRequest)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetImportRequestArgs) error); ok {
- r1 = returnFunc(context1, getImportRequestArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetImportRequest_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetImportRequest'
-type Client_GetImportRequest_Call struct {
- *mock.Call
-}
-
-// GetImportRequest is a helper method to define mock.On call
-// - context1
-// - getImportRequestArgs
-func (_e *Client_Expecter) GetImportRequest(context1 interface{}, getImportRequestArgs interface{}) *Client_GetImportRequest_Call {
- return &Client_GetImportRequest_Call{Call: _e.mock.On("GetImportRequest", context1, getImportRequestArgs)}
-}
-
-func (_c *Client_GetImportRequest_Call) Run(run func(context1 context.Context, getImportRequestArgs git.GetImportRequestArgs)) *Client_GetImportRequest_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetImportRequestArgs))
- })
- return _c
-}
-
-func (_c *Client_GetImportRequest_Call) Return(gitImportRequest *git.GitImportRequest, err error) *Client_GetImportRequest_Call {
- _c.Call.Return(gitImportRequest, err)
- return _c
-}
-
-func (_c *Client_GetImportRequest_Call) RunAndReturn(run func(context1 context.Context, getImportRequestArgs git.GetImportRequestArgs) (*git.GitImportRequest, error)) *Client_GetImportRequest_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetItem provides a mock function for the type Client
-func (_mock *Client) GetItem(context1 context.Context, getItemArgs git.GetItemArgs) (*git.GitItem, error) {
- ret := _mock.Called(context1, getItemArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetItem")
- }
-
- var r0 *git.GitItem
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetItemArgs) (*git.GitItem, error)); ok {
- return returnFunc(context1, getItemArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetItemArgs) *git.GitItem); ok {
- r0 = returnFunc(context1, getItemArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*git.GitItem)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetItemArgs) error); ok {
- r1 = returnFunc(context1, getItemArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetItem_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetItem'
-type Client_GetItem_Call struct {
- *mock.Call
-}
-
-// GetItem is a helper method to define mock.On call
-// - context1
-// - getItemArgs
-func (_e *Client_Expecter) GetItem(context1 interface{}, getItemArgs interface{}) *Client_GetItem_Call {
- return &Client_GetItem_Call{Call: _e.mock.On("GetItem", context1, getItemArgs)}
-}
-
-func (_c *Client_GetItem_Call) Run(run func(context1 context.Context, getItemArgs git.GetItemArgs)) *Client_GetItem_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetItemArgs))
- })
- return _c
-}
-
-func (_c *Client_GetItem_Call) Return(gitItem *git.GitItem, err error) *Client_GetItem_Call {
- _c.Call.Return(gitItem, err)
- return _c
-}
-
-func (_c *Client_GetItem_Call) RunAndReturn(run func(context1 context.Context, getItemArgs git.GetItemArgs) (*git.GitItem, error)) *Client_GetItem_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetItemContent provides a mock function for the type Client
-func (_mock *Client) GetItemContent(context1 context.Context, getItemContentArgs git.GetItemContentArgs) (io.ReadCloser, error) {
- ret := _mock.Called(context1, getItemContentArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetItemContent")
- }
-
- var r0 io.ReadCloser
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetItemContentArgs) (io.ReadCloser, error)); ok {
- return returnFunc(context1, getItemContentArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetItemContentArgs) io.ReadCloser); ok {
- r0 = returnFunc(context1, getItemContentArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(io.ReadCloser)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetItemContentArgs) error); ok {
- r1 = returnFunc(context1, getItemContentArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetItemContent_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetItemContent'
-type Client_GetItemContent_Call struct {
- *mock.Call
-}
-
-// GetItemContent is a helper method to define mock.On call
-// - context1
-// - getItemContentArgs
-func (_e *Client_Expecter) GetItemContent(context1 interface{}, getItemContentArgs interface{}) *Client_GetItemContent_Call {
- return &Client_GetItemContent_Call{Call: _e.mock.On("GetItemContent", context1, getItemContentArgs)}
-}
-
-func (_c *Client_GetItemContent_Call) Run(run func(context1 context.Context, getItemContentArgs git.GetItemContentArgs)) *Client_GetItemContent_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetItemContentArgs))
- })
- return _c
-}
-
-func (_c *Client_GetItemContent_Call) Return(readCloser io.ReadCloser, err error) *Client_GetItemContent_Call {
- _c.Call.Return(readCloser, err)
- return _c
-}
-
-func (_c *Client_GetItemContent_Call) RunAndReturn(run func(context1 context.Context, getItemContentArgs git.GetItemContentArgs) (io.ReadCloser, error)) *Client_GetItemContent_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetItemText provides a mock function for the type Client
-func (_mock *Client) GetItemText(context1 context.Context, getItemTextArgs git.GetItemTextArgs) (io.ReadCloser, error) {
- ret := _mock.Called(context1, getItemTextArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetItemText")
- }
-
- var r0 io.ReadCloser
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetItemTextArgs) (io.ReadCloser, error)); ok {
- return returnFunc(context1, getItemTextArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetItemTextArgs) io.ReadCloser); ok {
- r0 = returnFunc(context1, getItemTextArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(io.ReadCloser)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetItemTextArgs) error); ok {
- r1 = returnFunc(context1, getItemTextArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetItemText_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetItemText'
-type Client_GetItemText_Call struct {
- *mock.Call
-}
-
-// GetItemText is a helper method to define mock.On call
-// - context1
-// - getItemTextArgs
-func (_e *Client_Expecter) GetItemText(context1 interface{}, getItemTextArgs interface{}) *Client_GetItemText_Call {
- return &Client_GetItemText_Call{Call: _e.mock.On("GetItemText", context1, getItemTextArgs)}
-}
-
-func (_c *Client_GetItemText_Call) Run(run func(context1 context.Context, getItemTextArgs git.GetItemTextArgs)) *Client_GetItemText_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetItemTextArgs))
- })
- return _c
-}
-
-func (_c *Client_GetItemText_Call) Return(readCloser io.ReadCloser, err error) *Client_GetItemText_Call {
- _c.Call.Return(readCloser, err)
- return _c
-}
-
-func (_c *Client_GetItemText_Call) RunAndReturn(run func(context1 context.Context, getItemTextArgs git.GetItemTextArgs) (io.ReadCloser, error)) *Client_GetItemText_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetItemZip provides a mock function for the type Client
-func (_mock *Client) GetItemZip(context1 context.Context, getItemZipArgs git.GetItemZipArgs) (io.ReadCloser, error) {
- ret := _mock.Called(context1, getItemZipArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetItemZip")
- }
-
- var r0 io.ReadCloser
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetItemZipArgs) (io.ReadCloser, error)); ok {
- return returnFunc(context1, getItemZipArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetItemZipArgs) io.ReadCloser); ok {
- r0 = returnFunc(context1, getItemZipArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(io.ReadCloser)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetItemZipArgs) error); ok {
- r1 = returnFunc(context1, getItemZipArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetItemZip_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetItemZip'
-type Client_GetItemZip_Call struct {
- *mock.Call
-}
-
-// GetItemZip is a helper method to define mock.On call
-// - context1
-// - getItemZipArgs
-func (_e *Client_Expecter) GetItemZip(context1 interface{}, getItemZipArgs interface{}) *Client_GetItemZip_Call {
- return &Client_GetItemZip_Call{Call: _e.mock.On("GetItemZip", context1, getItemZipArgs)}
-}
-
-func (_c *Client_GetItemZip_Call) Run(run func(context1 context.Context, getItemZipArgs git.GetItemZipArgs)) *Client_GetItemZip_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetItemZipArgs))
- })
- return _c
-}
-
-func (_c *Client_GetItemZip_Call) Return(readCloser io.ReadCloser, err error) *Client_GetItemZip_Call {
- _c.Call.Return(readCloser, err)
- return _c
-}
-
-func (_c *Client_GetItemZip_Call) RunAndReturn(run func(context1 context.Context, getItemZipArgs git.GetItemZipArgs) (io.ReadCloser, error)) *Client_GetItemZip_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetItems provides a mock function for the type Client
-func (_mock *Client) GetItems(context1 context.Context, getItemsArgs git.GetItemsArgs) (*[]git.GitItem, error) {
- ret := _mock.Called(context1, getItemsArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetItems")
- }
-
- var r0 *[]git.GitItem
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetItemsArgs) (*[]git.GitItem, error)); ok {
- return returnFunc(context1, getItemsArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetItemsArgs) *[]git.GitItem); ok {
- r0 = returnFunc(context1, getItemsArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*[]git.GitItem)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetItemsArgs) error); ok {
- r1 = returnFunc(context1, getItemsArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetItems_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetItems'
-type Client_GetItems_Call struct {
- *mock.Call
-}
-
-// GetItems is a helper method to define mock.On call
-// - context1
-// - getItemsArgs
-func (_e *Client_Expecter) GetItems(context1 interface{}, getItemsArgs interface{}) *Client_GetItems_Call {
- return &Client_GetItems_Call{Call: _e.mock.On("GetItems", context1, getItemsArgs)}
-}
-
-func (_c *Client_GetItems_Call) Run(run func(context1 context.Context, getItemsArgs git.GetItemsArgs)) *Client_GetItems_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetItemsArgs))
- })
- return _c
-}
-
-func (_c *Client_GetItems_Call) Return(gitItems *[]git.GitItem, err error) *Client_GetItems_Call {
- _c.Call.Return(gitItems, err)
- return _c
-}
-
-func (_c *Client_GetItems_Call) RunAndReturn(run func(context1 context.Context, getItemsArgs git.GetItemsArgs) (*[]git.GitItem, error)) *Client_GetItems_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetItemsBatch provides a mock function for the type Client
-func (_mock *Client) GetItemsBatch(context1 context.Context, getItemsBatchArgs git.GetItemsBatchArgs) (*[][]git.GitItem, error) {
- ret := _mock.Called(context1, getItemsBatchArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetItemsBatch")
- }
-
- var r0 *[][]git.GitItem
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetItemsBatchArgs) (*[][]git.GitItem, error)); ok {
- return returnFunc(context1, getItemsBatchArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetItemsBatchArgs) *[][]git.GitItem); ok {
- r0 = returnFunc(context1, getItemsBatchArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*[][]git.GitItem)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetItemsBatchArgs) error); ok {
- r1 = returnFunc(context1, getItemsBatchArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetItemsBatch_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetItemsBatch'
-type Client_GetItemsBatch_Call struct {
- *mock.Call
-}
-
-// GetItemsBatch is a helper method to define mock.On call
-// - context1
-// - getItemsBatchArgs
-func (_e *Client_Expecter) GetItemsBatch(context1 interface{}, getItemsBatchArgs interface{}) *Client_GetItemsBatch_Call {
- return &Client_GetItemsBatch_Call{Call: _e.mock.On("GetItemsBatch", context1, getItemsBatchArgs)}
-}
-
-func (_c *Client_GetItemsBatch_Call) Run(run func(context1 context.Context, getItemsBatchArgs git.GetItemsBatchArgs)) *Client_GetItemsBatch_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetItemsBatchArgs))
- })
- return _c
-}
-
-func (_c *Client_GetItemsBatch_Call) Return(gitItemss *[][]git.GitItem, err error) *Client_GetItemsBatch_Call {
- _c.Call.Return(gitItemss, err)
- return _c
-}
-
-func (_c *Client_GetItemsBatch_Call) RunAndReturn(run func(context1 context.Context, getItemsBatchArgs git.GetItemsBatchArgs) (*[][]git.GitItem, error)) *Client_GetItemsBatch_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetLikes provides a mock function for the type Client
-func (_mock *Client) GetLikes(context1 context.Context, getLikesArgs git.GetLikesArgs) (*[]webapi.IdentityRef, error) {
- ret := _mock.Called(context1, getLikesArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetLikes")
- }
-
- var r0 *[]webapi.IdentityRef
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetLikesArgs) (*[]webapi.IdentityRef, error)); ok {
- return returnFunc(context1, getLikesArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetLikesArgs) *[]webapi.IdentityRef); ok {
- r0 = returnFunc(context1, getLikesArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*[]webapi.IdentityRef)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetLikesArgs) error); ok {
- r1 = returnFunc(context1, getLikesArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetLikes_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetLikes'
-type Client_GetLikes_Call struct {
- *mock.Call
-}
-
-// GetLikes is a helper method to define mock.On call
-// - context1
-// - getLikesArgs
-func (_e *Client_Expecter) GetLikes(context1 interface{}, getLikesArgs interface{}) *Client_GetLikes_Call {
- return &Client_GetLikes_Call{Call: _e.mock.On("GetLikes", context1, getLikesArgs)}
-}
-
-func (_c *Client_GetLikes_Call) Run(run func(context1 context.Context, getLikesArgs git.GetLikesArgs)) *Client_GetLikes_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetLikesArgs))
- })
- return _c
-}
-
-func (_c *Client_GetLikes_Call) Return(identityRefs *[]webapi.IdentityRef, err error) *Client_GetLikes_Call {
- _c.Call.Return(identityRefs, err)
- return _c
-}
-
-func (_c *Client_GetLikes_Call) RunAndReturn(run func(context1 context.Context, getLikesArgs git.GetLikesArgs) (*[]webapi.IdentityRef, error)) *Client_GetLikes_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetMergeBases provides a mock function for the type Client
-func (_mock *Client) GetMergeBases(context1 context.Context, getMergeBasesArgs git.GetMergeBasesArgs) (*[]git.GitCommitRef, error) {
- ret := _mock.Called(context1, getMergeBasesArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetMergeBases")
- }
-
- var r0 *[]git.GitCommitRef
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetMergeBasesArgs) (*[]git.GitCommitRef, error)); ok {
- return returnFunc(context1, getMergeBasesArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetMergeBasesArgs) *[]git.GitCommitRef); ok {
- r0 = returnFunc(context1, getMergeBasesArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*[]git.GitCommitRef)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetMergeBasesArgs) error); ok {
- r1 = returnFunc(context1, getMergeBasesArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetMergeBases_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetMergeBases'
-type Client_GetMergeBases_Call struct {
- *mock.Call
-}
-
-// GetMergeBases is a helper method to define mock.On call
-// - context1
-// - getMergeBasesArgs
-func (_e *Client_Expecter) GetMergeBases(context1 interface{}, getMergeBasesArgs interface{}) *Client_GetMergeBases_Call {
- return &Client_GetMergeBases_Call{Call: _e.mock.On("GetMergeBases", context1, getMergeBasesArgs)}
-}
-
-func (_c *Client_GetMergeBases_Call) Run(run func(context1 context.Context, getMergeBasesArgs git.GetMergeBasesArgs)) *Client_GetMergeBases_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetMergeBasesArgs))
- })
- return _c
-}
-
-func (_c *Client_GetMergeBases_Call) Return(gitCommitRefs *[]git.GitCommitRef, err error) *Client_GetMergeBases_Call {
- _c.Call.Return(gitCommitRefs, err)
- return _c
-}
-
-func (_c *Client_GetMergeBases_Call) RunAndReturn(run func(context1 context.Context, getMergeBasesArgs git.GetMergeBasesArgs) (*[]git.GitCommitRef, error)) *Client_GetMergeBases_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetMergeRequest provides a mock function for the type Client
-func (_mock *Client) GetMergeRequest(context1 context.Context, getMergeRequestArgs git.GetMergeRequestArgs) (*git.GitMerge, error) {
- ret := _mock.Called(context1, getMergeRequestArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetMergeRequest")
- }
-
- var r0 *git.GitMerge
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetMergeRequestArgs) (*git.GitMerge, error)); ok {
- return returnFunc(context1, getMergeRequestArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetMergeRequestArgs) *git.GitMerge); ok {
- r0 = returnFunc(context1, getMergeRequestArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*git.GitMerge)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetMergeRequestArgs) error); ok {
- r1 = returnFunc(context1, getMergeRequestArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetMergeRequest_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetMergeRequest'
-type Client_GetMergeRequest_Call struct {
- *mock.Call
-}
-
-// GetMergeRequest is a helper method to define mock.On call
-// - context1
-// - getMergeRequestArgs
-func (_e *Client_Expecter) GetMergeRequest(context1 interface{}, getMergeRequestArgs interface{}) *Client_GetMergeRequest_Call {
- return &Client_GetMergeRequest_Call{Call: _e.mock.On("GetMergeRequest", context1, getMergeRequestArgs)}
-}
-
-func (_c *Client_GetMergeRequest_Call) Run(run func(context1 context.Context, getMergeRequestArgs git.GetMergeRequestArgs)) *Client_GetMergeRequest_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetMergeRequestArgs))
- })
- return _c
-}
-
-func (_c *Client_GetMergeRequest_Call) Return(gitMerge *git.GitMerge, err error) *Client_GetMergeRequest_Call {
- _c.Call.Return(gitMerge, err)
- return _c
-}
-
-func (_c *Client_GetMergeRequest_Call) RunAndReturn(run func(context1 context.Context, getMergeRequestArgs git.GetMergeRequestArgs) (*git.GitMerge, error)) *Client_GetMergeRequest_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetPermission provides a mock function for the type Client
-func (_mock *Client) GetPermission(context1 context.Context, getPermissionArgs git.GetPermissionArgs) (*bool, error) {
- ret := _mock.Called(context1, getPermissionArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetPermission")
- }
-
- var r0 *bool
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetPermissionArgs) (*bool, error)); ok {
- return returnFunc(context1, getPermissionArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetPermissionArgs) *bool); ok {
- r0 = returnFunc(context1, getPermissionArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*bool)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetPermissionArgs) error); ok {
- r1 = returnFunc(context1, getPermissionArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetPermission_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetPermission'
-type Client_GetPermission_Call struct {
- *mock.Call
-}
-
-// GetPermission is a helper method to define mock.On call
-// - context1
-// - getPermissionArgs
-func (_e *Client_Expecter) GetPermission(context1 interface{}, getPermissionArgs interface{}) *Client_GetPermission_Call {
- return &Client_GetPermission_Call{Call: _e.mock.On("GetPermission", context1, getPermissionArgs)}
-}
-
-func (_c *Client_GetPermission_Call) Run(run func(context1 context.Context, getPermissionArgs git.GetPermissionArgs)) *Client_GetPermission_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetPermissionArgs))
- })
- return _c
-}
-
-func (_c *Client_GetPermission_Call) Return(b *bool, err error) *Client_GetPermission_Call {
- _c.Call.Return(b, err)
- return _c
-}
-
-func (_c *Client_GetPermission_Call) RunAndReturn(run func(context1 context.Context, getPermissionArgs git.GetPermissionArgs) (*bool, error)) *Client_GetPermission_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetPolicyConfigurations provides a mock function for the type Client
-func (_mock *Client) GetPolicyConfigurations(context1 context.Context, getPolicyConfigurationsArgs git.GetPolicyConfigurationsArgs) (*git.GitPolicyConfigurationResponse, error) {
- ret := _mock.Called(context1, getPolicyConfigurationsArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetPolicyConfigurations")
- }
-
- var r0 *git.GitPolicyConfigurationResponse
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetPolicyConfigurationsArgs) (*git.GitPolicyConfigurationResponse, error)); ok {
- return returnFunc(context1, getPolicyConfigurationsArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetPolicyConfigurationsArgs) *git.GitPolicyConfigurationResponse); ok {
- r0 = returnFunc(context1, getPolicyConfigurationsArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*git.GitPolicyConfigurationResponse)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetPolicyConfigurationsArgs) error); ok {
- r1 = returnFunc(context1, getPolicyConfigurationsArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetPolicyConfigurations_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetPolicyConfigurations'
-type Client_GetPolicyConfigurations_Call struct {
- *mock.Call
-}
-
-// GetPolicyConfigurations is a helper method to define mock.On call
-// - context1
-// - getPolicyConfigurationsArgs
-func (_e *Client_Expecter) GetPolicyConfigurations(context1 interface{}, getPolicyConfigurationsArgs interface{}) *Client_GetPolicyConfigurations_Call {
- return &Client_GetPolicyConfigurations_Call{Call: _e.mock.On("GetPolicyConfigurations", context1, getPolicyConfigurationsArgs)}
-}
-
-func (_c *Client_GetPolicyConfigurations_Call) Run(run func(context1 context.Context, getPolicyConfigurationsArgs git.GetPolicyConfigurationsArgs)) *Client_GetPolicyConfigurations_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetPolicyConfigurationsArgs))
- })
- return _c
-}
-
-func (_c *Client_GetPolicyConfigurations_Call) Return(gitPolicyConfigurationResponse *git.GitPolicyConfigurationResponse, err error) *Client_GetPolicyConfigurations_Call {
- _c.Call.Return(gitPolicyConfigurationResponse, err)
- return _c
-}
-
-func (_c *Client_GetPolicyConfigurations_Call) RunAndReturn(run func(context1 context.Context, getPolicyConfigurationsArgs git.GetPolicyConfigurationsArgs) (*git.GitPolicyConfigurationResponse, error)) *Client_GetPolicyConfigurations_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetPullRequest provides a mock function for the type Client
-func (_mock *Client) GetPullRequest(context1 context.Context, getPullRequestArgs git.GetPullRequestArgs) (*git.GitPullRequest, error) {
- ret := _mock.Called(context1, getPullRequestArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetPullRequest")
- }
-
- var r0 *git.GitPullRequest
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetPullRequestArgs) (*git.GitPullRequest, error)); ok {
- return returnFunc(context1, getPullRequestArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetPullRequestArgs) *git.GitPullRequest); ok {
- r0 = returnFunc(context1, getPullRequestArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*git.GitPullRequest)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetPullRequestArgs) error); ok {
- r1 = returnFunc(context1, getPullRequestArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetPullRequest_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetPullRequest'
-type Client_GetPullRequest_Call struct {
- *mock.Call
-}
-
-// GetPullRequest is a helper method to define mock.On call
-// - context1
-// - getPullRequestArgs
-func (_e *Client_Expecter) GetPullRequest(context1 interface{}, getPullRequestArgs interface{}) *Client_GetPullRequest_Call {
- return &Client_GetPullRequest_Call{Call: _e.mock.On("GetPullRequest", context1, getPullRequestArgs)}
-}
-
-func (_c *Client_GetPullRequest_Call) Run(run func(context1 context.Context, getPullRequestArgs git.GetPullRequestArgs)) *Client_GetPullRequest_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetPullRequestArgs))
- })
- return _c
-}
-
-func (_c *Client_GetPullRequest_Call) Return(gitPullRequest *git.GitPullRequest, err error) *Client_GetPullRequest_Call {
- _c.Call.Return(gitPullRequest, err)
- return _c
-}
-
-func (_c *Client_GetPullRequest_Call) RunAndReturn(run func(context1 context.Context, getPullRequestArgs git.GetPullRequestArgs) (*git.GitPullRequest, error)) *Client_GetPullRequest_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetPullRequestById provides a mock function for the type Client
-func (_mock *Client) GetPullRequestById(context1 context.Context, getPullRequestByIdArgs git.GetPullRequestByIdArgs) (*git.GitPullRequest, error) {
- ret := _mock.Called(context1, getPullRequestByIdArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetPullRequestById")
- }
-
- var r0 *git.GitPullRequest
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetPullRequestByIdArgs) (*git.GitPullRequest, error)); ok {
- return returnFunc(context1, getPullRequestByIdArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetPullRequestByIdArgs) *git.GitPullRequest); ok {
- r0 = returnFunc(context1, getPullRequestByIdArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*git.GitPullRequest)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetPullRequestByIdArgs) error); ok {
- r1 = returnFunc(context1, getPullRequestByIdArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetPullRequestById_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetPullRequestById'
-type Client_GetPullRequestById_Call struct {
- *mock.Call
-}
-
-// GetPullRequestById is a helper method to define mock.On call
-// - context1
-// - getPullRequestByIdArgs
-func (_e *Client_Expecter) GetPullRequestById(context1 interface{}, getPullRequestByIdArgs interface{}) *Client_GetPullRequestById_Call {
- return &Client_GetPullRequestById_Call{Call: _e.mock.On("GetPullRequestById", context1, getPullRequestByIdArgs)}
-}
-
-func (_c *Client_GetPullRequestById_Call) Run(run func(context1 context.Context, getPullRequestByIdArgs git.GetPullRequestByIdArgs)) *Client_GetPullRequestById_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetPullRequestByIdArgs))
- })
- return _c
-}
-
-func (_c *Client_GetPullRequestById_Call) Return(gitPullRequest *git.GitPullRequest, err error) *Client_GetPullRequestById_Call {
- _c.Call.Return(gitPullRequest, err)
- return _c
-}
-
-func (_c *Client_GetPullRequestById_Call) RunAndReturn(run func(context1 context.Context, getPullRequestByIdArgs git.GetPullRequestByIdArgs) (*git.GitPullRequest, error)) *Client_GetPullRequestById_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetPullRequestCommits provides a mock function for the type Client
-func (_mock *Client) GetPullRequestCommits(context1 context.Context, getPullRequestCommitsArgs git.GetPullRequestCommitsArgs) (*git.GetPullRequestCommitsResponseValue, error) {
- ret := _mock.Called(context1, getPullRequestCommitsArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetPullRequestCommits")
- }
-
- var r0 *git.GetPullRequestCommitsResponseValue
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetPullRequestCommitsArgs) (*git.GetPullRequestCommitsResponseValue, error)); ok {
- return returnFunc(context1, getPullRequestCommitsArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetPullRequestCommitsArgs) *git.GetPullRequestCommitsResponseValue); ok {
- r0 = returnFunc(context1, getPullRequestCommitsArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*git.GetPullRequestCommitsResponseValue)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetPullRequestCommitsArgs) error); ok {
- r1 = returnFunc(context1, getPullRequestCommitsArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetPullRequestCommits_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetPullRequestCommits'
-type Client_GetPullRequestCommits_Call struct {
- *mock.Call
-}
-
-// GetPullRequestCommits is a helper method to define mock.On call
-// - context1
-// - getPullRequestCommitsArgs
-func (_e *Client_Expecter) GetPullRequestCommits(context1 interface{}, getPullRequestCommitsArgs interface{}) *Client_GetPullRequestCommits_Call {
- return &Client_GetPullRequestCommits_Call{Call: _e.mock.On("GetPullRequestCommits", context1, getPullRequestCommitsArgs)}
-}
-
-func (_c *Client_GetPullRequestCommits_Call) Run(run func(context1 context.Context, getPullRequestCommitsArgs git.GetPullRequestCommitsArgs)) *Client_GetPullRequestCommits_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetPullRequestCommitsArgs))
- })
- return _c
-}
-
-func (_c *Client_GetPullRequestCommits_Call) Return(getPullRequestCommitsResponseValue *git.GetPullRequestCommitsResponseValue, err error) *Client_GetPullRequestCommits_Call {
- _c.Call.Return(getPullRequestCommitsResponseValue, err)
- return _c
-}
-
-func (_c *Client_GetPullRequestCommits_Call) RunAndReturn(run func(context1 context.Context, getPullRequestCommitsArgs git.GetPullRequestCommitsArgs) (*git.GetPullRequestCommitsResponseValue, error)) *Client_GetPullRequestCommits_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetPullRequestIteration provides a mock function for the type Client
-func (_mock *Client) GetPullRequestIteration(context1 context.Context, getPullRequestIterationArgs git.GetPullRequestIterationArgs) (*git.GitPullRequestIteration, error) {
- ret := _mock.Called(context1, getPullRequestIterationArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetPullRequestIteration")
- }
-
- var r0 *git.GitPullRequestIteration
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetPullRequestIterationArgs) (*git.GitPullRequestIteration, error)); ok {
- return returnFunc(context1, getPullRequestIterationArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetPullRequestIterationArgs) *git.GitPullRequestIteration); ok {
- r0 = returnFunc(context1, getPullRequestIterationArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*git.GitPullRequestIteration)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetPullRequestIterationArgs) error); ok {
- r1 = returnFunc(context1, getPullRequestIterationArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetPullRequestIteration_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetPullRequestIteration'
-type Client_GetPullRequestIteration_Call struct {
- *mock.Call
-}
-
-// GetPullRequestIteration is a helper method to define mock.On call
-// - context1
-// - getPullRequestIterationArgs
-func (_e *Client_Expecter) GetPullRequestIteration(context1 interface{}, getPullRequestIterationArgs interface{}) *Client_GetPullRequestIteration_Call {
- return &Client_GetPullRequestIteration_Call{Call: _e.mock.On("GetPullRequestIteration", context1, getPullRequestIterationArgs)}
-}
-
-func (_c *Client_GetPullRequestIteration_Call) Run(run func(context1 context.Context, getPullRequestIterationArgs git.GetPullRequestIterationArgs)) *Client_GetPullRequestIteration_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetPullRequestIterationArgs))
- })
- return _c
-}
-
-func (_c *Client_GetPullRequestIteration_Call) Return(gitPullRequestIteration *git.GitPullRequestIteration, err error) *Client_GetPullRequestIteration_Call {
- _c.Call.Return(gitPullRequestIteration, err)
- return _c
-}
-
-func (_c *Client_GetPullRequestIteration_Call) RunAndReturn(run func(context1 context.Context, getPullRequestIterationArgs git.GetPullRequestIterationArgs) (*git.GitPullRequestIteration, error)) *Client_GetPullRequestIteration_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetPullRequestIterationChanges provides a mock function for the type Client
-func (_mock *Client) GetPullRequestIterationChanges(context1 context.Context, getPullRequestIterationChangesArgs git.GetPullRequestIterationChangesArgs) (*git.GitPullRequestIterationChanges, error) {
- ret := _mock.Called(context1, getPullRequestIterationChangesArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetPullRequestIterationChanges")
- }
-
- var r0 *git.GitPullRequestIterationChanges
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetPullRequestIterationChangesArgs) (*git.GitPullRequestIterationChanges, error)); ok {
- return returnFunc(context1, getPullRequestIterationChangesArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetPullRequestIterationChangesArgs) *git.GitPullRequestIterationChanges); ok {
- r0 = returnFunc(context1, getPullRequestIterationChangesArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*git.GitPullRequestIterationChanges)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetPullRequestIterationChangesArgs) error); ok {
- r1 = returnFunc(context1, getPullRequestIterationChangesArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetPullRequestIterationChanges_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetPullRequestIterationChanges'
-type Client_GetPullRequestIterationChanges_Call struct {
- *mock.Call
-}
-
-// GetPullRequestIterationChanges is a helper method to define mock.On call
-// - context1
-// - getPullRequestIterationChangesArgs
-func (_e *Client_Expecter) GetPullRequestIterationChanges(context1 interface{}, getPullRequestIterationChangesArgs interface{}) *Client_GetPullRequestIterationChanges_Call {
- return &Client_GetPullRequestIterationChanges_Call{Call: _e.mock.On("GetPullRequestIterationChanges", context1, getPullRequestIterationChangesArgs)}
-}
-
-func (_c *Client_GetPullRequestIterationChanges_Call) Run(run func(context1 context.Context, getPullRequestIterationChangesArgs git.GetPullRequestIterationChangesArgs)) *Client_GetPullRequestIterationChanges_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetPullRequestIterationChangesArgs))
- })
- return _c
-}
-
-func (_c *Client_GetPullRequestIterationChanges_Call) Return(gitPullRequestIterationChanges *git.GitPullRequestIterationChanges, err error) *Client_GetPullRequestIterationChanges_Call {
- _c.Call.Return(gitPullRequestIterationChanges, err)
- return _c
-}
-
-func (_c *Client_GetPullRequestIterationChanges_Call) RunAndReturn(run func(context1 context.Context, getPullRequestIterationChangesArgs git.GetPullRequestIterationChangesArgs) (*git.GitPullRequestIterationChanges, error)) *Client_GetPullRequestIterationChanges_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetPullRequestIterationCommits provides a mock function for the type Client
-func (_mock *Client) GetPullRequestIterationCommits(context1 context.Context, getPullRequestIterationCommitsArgs git.GetPullRequestIterationCommitsArgs) (*[]git.GitCommitRef, error) {
- ret := _mock.Called(context1, getPullRequestIterationCommitsArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetPullRequestIterationCommits")
- }
-
- var r0 *[]git.GitCommitRef
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetPullRequestIterationCommitsArgs) (*[]git.GitCommitRef, error)); ok {
- return returnFunc(context1, getPullRequestIterationCommitsArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetPullRequestIterationCommitsArgs) *[]git.GitCommitRef); ok {
- r0 = returnFunc(context1, getPullRequestIterationCommitsArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*[]git.GitCommitRef)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetPullRequestIterationCommitsArgs) error); ok {
- r1 = returnFunc(context1, getPullRequestIterationCommitsArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetPullRequestIterationCommits_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetPullRequestIterationCommits'
-type Client_GetPullRequestIterationCommits_Call struct {
- *mock.Call
-}
-
-// GetPullRequestIterationCommits is a helper method to define mock.On call
-// - context1
-// - getPullRequestIterationCommitsArgs
-func (_e *Client_Expecter) GetPullRequestIterationCommits(context1 interface{}, getPullRequestIterationCommitsArgs interface{}) *Client_GetPullRequestIterationCommits_Call {
- return &Client_GetPullRequestIterationCommits_Call{Call: _e.mock.On("GetPullRequestIterationCommits", context1, getPullRequestIterationCommitsArgs)}
-}
-
-func (_c *Client_GetPullRequestIterationCommits_Call) Run(run func(context1 context.Context, getPullRequestIterationCommitsArgs git.GetPullRequestIterationCommitsArgs)) *Client_GetPullRequestIterationCommits_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetPullRequestIterationCommitsArgs))
- })
- return _c
-}
-
-func (_c *Client_GetPullRequestIterationCommits_Call) Return(gitCommitRefs *[]git.GitCommitRef, err error) *Client_GetPullRequestIterationCommits_Call {
- _c.Call.Return(gitCommitRefs, err)
- return _c
-}
-
-func (_c *Client_GetPullRequestIterationCommits_Call) RunAndReturn(run func(context1 context.Context, getPullRequestIterationCommitsArgs git.GetPullRequestIterationCommitsArgs) (*[]git.GitCommitRef, error)) *Client_GetPullRequestIterationCommits_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetPullRequestIterationStatus provides a mock function for the type Client
-func (_mock *Client) GetPullRequestIterationStatus(context1 context.Context, getPullRequestIterationStatusArgs git.GetPullRequestIterationStatusArgs) (*git.GitPullRequestStatus, error) {
- ret := _mock.Called(context1, getPullRequestIterationStatusArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetPullRequestIterationStatus")
- }
-
- var r0 *git.GitPullRequestStatus
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetPullRequestIterationStatusArgs) (*git.GitPullRequestStatus, error)); ok {
- return returnFunc(context1, getPullRequestIterationStatusArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetPullRequestIterationStatusArgs) *git.GitPullRequestStatus); ok {
- r0 = returnFunc(context1, getPullRequestIterationStatusArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*git.GitPullRequestStatus)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetPullRequestIterationStatusArgs) error); ok {
- r1 = returnFunc(context1, getPullRequestIterationStatusArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetPullRequestIterationStatus_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetPullRequestIterationStatus'
-type Client_GetPullRequestIterationStatus_Call struct {
- *mock.Call
-}
-
-// GetPullRequestIterationStatus is a helper method to define mock.On call
-// - context1
-// - getPullRequestIterationStatusArgs
-func (_e *Client_Expecter) GetPullRequestIterationStatus(context1 interface{}, getPullRequestIterationStatusArgs interface{}) *Client_GetPullRequestIterationStatus_Call {
- return &Client_GetPullRequestIterationStatus_Call{Call: _e.mock.On("GetPullRequestIterationStatus", context1, getPullRequestIterationStatusArgs)}
-}
-
-func (_c *Client_GetPullRequestIterationStatus_Call) Run(run func(context1 context.Context, getPullRequestIterationStatusArgs git.GetPullRequestIterationStatusArgs)) *Client_GetPullRequestIterationStatus_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetPullRequestIterationStatusArgs))
- })
- return _c
-}
-
-func (_c *Client_GetPullRequestIterationStatus_Call) Return(gitPullRequestStatus *git.GitPullRequestStatus, err error) *Client_GetPullRequestIterationStatus_Call {
- _c.Call.Return(gitPullRequestStatus, err)
- return _c
-}
-
-func (_c *Client_GetPullRequestIterationStatus_Call) RunAndReturn(run func(context1 context.Context, getPullRequestIterationStatusArgs git.GetPullRequestIterationStatusArgs) (*git.GitPullRequestStatus, error)) *Client_GetPullRequestIterationStatus_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetPullRequestIterationStatuses provides a mock function for the type Client
-func (_mock *Client) GetPullRequestIterationStatuses(context1 context.Context, getPullRequestIterationStatusesArgs git.GetPullRequestIterationStatusesArgs) (*[]git.GitPullRequestStatus, error) {
- ret := _mock.Called(context1, getPullRequestIterationStatusesArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetPullRequestIterationStatuses")
- }
-
- var r0 *[]git.GitPullRequestStatus
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetPullRequestIterationStatusesArgs) (*[]git.GitPullRequestStatus, error)); ok {
- return returnFunc(context1, getPullRequestIterationStatusesArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetPullRequestIterationStatusesArgs) *[]git.GitPullRequestStatus); ok {
- r0 = returnFunc(context1, getPullRequestIterationStatusesArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*[]git.GitPullRequestStatus)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetPullRequestIterationStatusesArgs) error); ok {
- r1 = returnFunc(context1, getPullRequestIterationStatusesArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetPullRequestIterationStatuses_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetPullRequestIterationStatuses'
-type Client_GetPullRequestIterationStatuses_Call struct {
- *mock.Call
-}
-
-// GetPullRequestIterationStatuses is a helper method to define mock.On call
-// - context1
-// - getPullRequestIterationStatusesArgs
-func (_e *Client_Expecter) GetPullRequestIterationStatuses(context1 interface{}, getPullRequestIterationStatusesArgs interface{}) *Client_GetPullRequestIterationStatuses_Call {
- return &Client_GetPullRequestIterationStatuses_Call{Call: _e.mock.On("GetPullRequestIterationStatuses", context1, getPullRequestIterationStatusesArgs)}
-}
-
-func (_c *Client_GetPullRequestIterationStatuses_Call) Run(run func(context1 context.Context, getPullRequestIterationStatusesArgs git.GetPullRequestIterationStatusesArgs)) *Client_GetPullRequestIterationStatuses_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetPullRequestIterationStatusesArgs))
- })
- return _c
-}
-
-func (_c *Client_GetPullRequestIterationStatuses_Call) Return(gitPullRequestStatuss *[]git.GitPullRequestStatus, err error) *Client_GetPullRequestIterationStatuses_Call {
- _c.Call.Return(gitPullRequestStatuss, err)
- return _c
-}
-
-func (_c *Client_GetPullRequestIterationStatuses_Call) RunAndReturn(run func(context1 context.Context, getPullRequestIterationStatusesArgs git.GetPullRequestIterationStatusesArgs) (*[]git.GitPullRequestStatus, error)) *Client_GetPullRequestIterationStatuses_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetPullRequestIterations provides a mock function for the type Client
-func (_mock *Client) GetPullRequestIterations(context1 context.Context, getPullRequestIterationsArgs git.GetPullRequestIterationsArgs) (*[]git.GitPullRequestIteration, error) {
- ret := _mock.Called(context1, getPullRequestIterationsArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetPullRequestIterations")
- }
-
- var r0 *[]git.GitPullRequestIteration
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetPullRequestIterationsArgs) (*[]git.GitPullRequestIteration, error)); ok {
- return returnFunc(context1, getPullRequestIterationsArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetPullRequestIterationsArgs) *[]git.GitPullRequestIteration); ok {
- r0 = returnFunc(context1, getPullRequestIterationsArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*[]git.GitPullRequestIteration)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetPullRequestIterationsArgs) error); ok {
- r1 = returnFunc(context1, getPullRequestIterationsArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetPullRequestIterations_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetPullRequestIterations'
-type Client_GetPullRequestIterations_Call struct {
- *mock.Call
-}
-
-// GetPullRequestIterations is a helper method to define mock.On call
-// - context1
-// - getPullRequestIterationsArgs
-func (_e *Client_Expecter) GetPullRequestIterations(context1 interface{}, getPullRequestIterationsArgs interface{}) *Client_GetPullRequestIterations_Call {
- return &Client_GetPullRequestIterations_Call{Call: _e.mock.On("GetPullRequestIterations", context1, getPullRequestIterationsArgs)}
-}
-
-func (_c *Client_GetPullRequestIterations_Call) Run(run func(context1 context.Context, getPullRequestIterationsArgs git.GetPullRequestIterationsArgs)) *Client_GetPullRequestIterations_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetPullRequestIterationsArgs))
- })
- return _c
-}
-
-func (_c *Client_GetPullRequestIterations_Call) Return(gitPullRequestIterations *[]git.GitPullRequestIteration, err error) *Client_GetPullRequestIterations_Call {
- _c.Call.Return(gitPullRequestIterations, err)
- return _c
-}
-
-func (_c *Client_GetPullRequestIterations_Call) RunAndReturn(run func(context1 context.Context, getPullRequestIterationsArgs git.GetPullRequestIterationsArgs) (*[]git.GitPullRequestIteration, error)) *Client_GetPullRequestIterations_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetPullRequestLabel provides a mock function for the type Client
-func (_mock *Client) GetPullRequestLabel(context1 context.Context, getPullRequestLabelArgs git.GetPullRequestLabelArgs) (*core.WebApiTagDefinition, error) {
- ret := _mock.Called(context1, getPullRequestLabelArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetPullRequestLabel")
- }
-
- var r0 *core.WebApiTagDefinition
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetPullRequestLabelArgs) (*core.WebApiTagDefinition, error)); ok {
- return returnFunc(context1, getPullRequestLabelArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetPullRequestLabelArgs) *core.WebApiTagDefinition); ok {
- r0 = returnFunc(context1, getPullRequestLabelArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*core.WebApiTagDefinition)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetPullRequestLabelArgs) error); ok {
- r1 = returnFunc(context1, getPullRequestLabelArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetPullRequestLabel_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetPullRequestLabel'
-type Client_GetPullRequestLabel_Call struct {
- *mock.Call
-}
-
-// GetPullRequestLabel is a helper method to define mock.On call
-// - context1
-// - getPullRequestLabelArgs
-func (_e *Client_Expecter) GetPullRequestLabel(context1 interface{}, getPullRequestLabelArgs interface{}) *Client_GetPullRequestLabel_Call {
- return &Client_GetPullRequestLabel_Call{Call: _e.mock.On("GetPullRequestLabel", context1, getPullRequestLabelArgs)}
-}
-
-func (_c *Client_GetPullRequestLabel_Call) Run(run func(context1 context.Context, getPullRequestLabelArgs git.GetPullRequestLabelArgs)) *Client_GetPullRequestLabel_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetPullRequestLabelArgs))
- })
- return _c
-}
-
-func (_c *Client_GetPullRequestLabel_Call) Return(webApiTagDefinition *core.WebApiTagDefinition, err error) *Client_GetPullRequestLabel_Call {
- _c.Call.Return(webApiTagDefinition, err)
- return _c
-}
-
-func (_c *Client_GetPullRequestLabel_Call) RunAndReturn(run func(context1 context.Context, getPullRequestLabelArgs git.GetPullRequestLabelArgs) (*core.WebApiTagDefinition, error)) *Client_GetPullRequestLabel_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetPullRequestLabels provides a mock function for the type Client
-func (_mock *Client) GetPullRequestLabels(context1 context.Context, getPullRequestLabelsArgs git.GetPullRequestLabelsArgs) (*[]core.WebApiTagDefinition, error) {
- ret := _mock.Called(context1, getPullRequestLabelsArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetPullRequestLabels")
- }
-
- var r0 *[]core.WebApiTagDefinition
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetPullRequestLabelsArgs) (*[]core.WebApiTagDefinition, error)); ok {
- return returnFunc(context1, getPullRequestLabelsArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetPullRequestLabelsArgs) *[]core.WebApiTagDefinition); ok {
- r0 = returnFunc(context1, getPullRequestLabelsArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*[]core.WebApiTagDefinition)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetPullRequestLabelsArgs) error); ok {
- r1 = returnFunc(context1, getPullRequestLabelsArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetPullRequestLabels_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetPullRequestLabels'
-type Client_GetPullRequestLabels_Call struct {
- *mock.Call
-}
-
-// GetPullRequestLabels is a helper method to define mock.On call
-// - context1
-// - getPullRequestLabelsArgs
-func (_e *Client_Expecter) GetPullRequestLabels(context1 interface{}, getPullRequestLabelsArgs interface{}) *Client_GetPullRequestLabels_Call {
- return &Client_GetPullRequestLabels_Call{Call: _e.mock.On("GetPullRequestLabels", context1, getPullRequestLabelsArgs)}
-}
-
-func (_c *Client_GetPullRequestLabels_Call) Run(run func(context1 context.Context, getPullRequestLabelsArgs git.GetPullRequestLabelsArgs)) *Client_GetPullRequestLabels_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetPullRequestLabelsArgs))
- })
- return _c
-}
-
-func (_c *Client_GetPullRequestLabels_Call) Return(webApiTagDefinitions *[]core.WebApiTagDefinition, err error) *Client_GetPullRequestLabels_Call {
- _c.Call.Return(webApiTagDefinitions, err)
- return _c
-}
-
-func (_c *Client_GetPullRequestLabels_Call) RunAndReturn(run func(context1 context.Context, getPullRequestLabelsArgs git.GetPullRequestLabelsArgs) (*[]core.WebApiTagDefinition, error)) *Client_GetPullRequestLabels_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetPullRequestProperties provides a mock function for the type Client
-func (_mock *Client) GetPullRequestProperties(context1 context.Context, getPullRequestPropertiesArgs git.GetPullRequestPropertiesArgs) (interface{}, error) {
- ret := _mock.Called(context1, getPullRequestPropertiesArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetPullRequestProperties")
- }
-
- var r0 interface{}
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetPullRequestPropertiesArgs) (interface{}, error)); ok {
- return returnFunc(context1, getPullRequestPropertiesArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetPullRequestPropertiesArgs) interface{}); ok {
- r0 = returnFunc(context1, getPullRequestPropertiesArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(interface{})
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetPullRequestPropertiesArgs) error); ok {
- r1 = returnFunc(context1, getPullRequestPropertiesArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetPullRequestProperties_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetPullRequestProperties'
-type Client_GetPullRequestProperties_Call struct {
- *mock.Call
-}
-
-// GetPullRequestProperties is a helper method to define mock.On call
-// - context1
-// - getPullRequestPropertiesArgs
-func (_e *Client_Expecter) GetPullRequestProperties(context1 interface{}, getPullRequestPropertiesArgs interface{}) *Client_GetPullRequestProperties_Call {
- return &Client_GetPullRequestProperties_Call{Call: _e.mock.On("GetPullRequestProperties", context1, getPullRequestPropertiesArgs)}
-}
-
-func (_c *Client_GetPullRequestProperties_Call) Run(run func(context1 context.Context, getPullRequestPropertiesArgs git.GetPullRequestPropertiesArgs)) *Client_GetPullRequestProperties_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetPullRequestPropertiesArgs))
- })
- return _c
-}
-
-func (_c *Client_GetPullRequestProperties_Call) Return(ifaceVal interface{}, err error) *Client_GetPullRequestProperties_Call {
- _c.Call.Return(ifaceVal, err)
- return _c
-}
-
-func (_c *Client_GetPullRequestProperties_Call) RunAndReturn(run func(context1 context.Context, getPullRequestPropertiesArgs git.GetPullRequestPropertiesArgs) (interface{}, error)) *Client_GetPullRequestProperties_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetPullRequestQuery provides a mock function for the type Client
-func (_mock *Client) GetPullRequestQuery(context1 context.Context, getPullRequestQueryArgs git.GetPullRequestQueryArgs) (*git.GitPullRequestQuery, error) {
- ret := _mock.Called(context1, getPullRequestQueryArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetPullRequestQuery")
- }
-
- var r0 *git.GitPullRequestQuery
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetPullRequestQueryArgs) (*git.GitPullRequestQuery, error)); ok {
- return returnFunc(context1, getPullRequestQueryArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetPullRequestQueryArgs) *git.GitPullRequestQuery); ok {
- r0 = returnFunc(context1, getPullRequestQueryArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*git.GitPullRequestQuery)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetPullRequestQueryArgs) error); ok {
- r1 = returnFunc(context1, getPullRequestQueryArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetPullRequestQuery_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetPullRequestQuery'
-type Client_GetPullRequestQuery_Call struct {
- *mock.Call
-}
-
-// GetPullRequestQuery is a helper method to define mock.On call
-// - context1
-// - getPullRequestQueryArgs
-func (_e *Client_Expecter) GetPullRequestQuery(context1 interface{}, getPullRequestQueryArgs interface{}) *Client_GetPullRequestQuery_Call {
- return &Client_GetPullRequestQuery_Call{Call: _e.mock.On("GetPullRequestQuery", context1, getPullRequestQueryArgs)}
-}
-
-func (_c *Client_GetPullRequestQuery_Call) Run(run func(context1 context.Context, getPullRequestQueryArgs git.GetPullRequestQueryArgs)) *Client_GetPullRequestQuery_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetPullRequestQueryArgs))
- })
- return _c
-}
-
-func (_c *Client_GetPullRequestQuery_Call) Return(gitPullRequestQuery *git.GitPullRequestQuery, err error) *Client_GetPullRequestQuery_Call {
- _c.Call.Return(gitPullRequestQuery, err)
- return _c
-}
-
-func (_c *Client_GetPullRequestQuery_Call) RunAndReturn(run func(context1 context.Context, getPullRequestQueryArgs git.GetPullRequestQueryArgs) (*git.GitPullRequestQuery, error)) *Client_GetPullRequestQuery_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetPullRequestReviewer provides a mock function for the type Client
-func (_mock *Client) GetPullRequestReviewer(context1 context.Context, getPullRequestReviewerArgs git.GetPullRequestReviewerArgs) (*git.IdentityRefWithVote, error) {
- ret := _mock.Called(context1, getPullRequestReviewerArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetPullRequestReviewer")
- }
-
- var r0 *git.IdentityRefWithVote
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetPullRequestReviewerArgs) (*git.IdentityRefWithVote, error)); ok {
- return returnFunc(context1, getPullRequestReviewerArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetPullRequestReviewerArgs) *git.IdentityRefWithVote); ok {
- r0 = returnFunc(context1, getPullRequestReviewerArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*git.IdentityRefWithVote)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetPullRequestReviewerArgs) error); ok {
- r1 = returnFunc(context1, getPullRequestReviewerArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetPullRequestReviewer_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetPullRequestReviewer'
-type Client_GetPullRequestReviewer_Call struct {
- *mock.Call
-}
-
-// GetPullRequestReviewer is a helper method to define mock.On call
-// - context1
-// - getPullRequestReviewerArgs
-func (_e *Client_Expecter) GetPullRequestReviewer(context1 interface{}, getPullRequestReviewerArgs interface{}) *Client_GetPullRequestReviewer_Call {
- return &Client_GetPullRequestReviewer_Call{Call: _e.mock.On("GetPullRequestReviewer", context1, getPullRequestReviewerArgs)}
-}
-
-func (_c *Client_GetPullRequestReviewer_Call) Run(run func(context1 context.Context, getPullRequestReviewerArgs git.GetPullRequestReviewerArgs)) *Client_GetPullRequestReviewer_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetPullRequestReviewerArgs))
- })
- return _c
-}
-
-func (_c *Client_GetPullRequestReviewer_Call) Return(identityRefWithVote *git.IdentityRefWithVote, err error) *Client_GetPullRequestReviewer_Call {
- _c.Call.Return(identityRefWithVote, err)
- return _c
-}
-
-func (_c *Client_GetPullRequestReviewer_Call) RunAndReturn(run func(context1 context.Context, getPullRequestReviewerArgs git.GetPullRequestReviewerArgs) (*git.IdentityRefWithVote, error)) *Client_GetPullRequestReviewer_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetPullRequestReviewers provides a mock function for the type Client
-func (_mock *Client) GetPullRequestReviewers(context1 context.Context, getPullRequestReviewersArgs git.GetPullRequestReviewersArgs) (*[]git.IdentityRefWithVote, error) {
- ret := _mock.Called(context1, getPullRequestReviewersArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetPullRequestReviewers")
- }
-
- var r0 *[]git.IdentityRefWithVote
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetPullRequestReviewersArgs) (*[]git.IdentityRefWithVote, error)); ok {
- return returnFunc(context1, getPullRequestReviewersArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetPullRequestReviewersArgs) *[]git.IdentityRefWithVote); ok {
- r0 = returnFunc(context1, getPullRequestReviewersArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*[]git.IdentityRefWithVote)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetPullRequestReviewersArgs) error); ok {
- r1 = returnFunc(context1, getPullRequestReviewersArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetPullRequestReviewers_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetPullRequestReviewers'
-type Client_GetPullRequestReviewers_Call struct {
- *mock.Call
-}
-
-// GetPullRequestReviewers is a helper method to define mock.On call
-// - context1
-// - getPullRequestReviewersArgs
-func (_e *Client_Expecter) GetPullRequestReviewers(context1 interface{}, getPullRequestReviewersArgs interface{}) *Client_GetPullRequestReviewers_Call {
- return &Client_GetPullRequestReviewers_Call{Call: _e.mock.On("GetPullRequestReviewers", context1, getPullRequestReviewersArgs)}
-}
-
-func (_c *Client_GetPullRequestReviewers_Call) Run(run func(context1 context.Context, getPullRequestReviewersArgs git.GetPullRequestReviewersArgs)) *Client_GetPullRequestReviewers_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetPullRequestReviewersArgs))
- })
- return _c
-}
-
-func (_c *Client_GetPullRequestReviewers_Call) Return(identityRefWithVotes *[]git.IdentityRefWithVote, err error) *Client_GetPullRequestReviewers_Call {
- _c.Call.Return(identityRefWithVotes, err)
- return _c
-}
-
-func (_c *Client_GetPullRequestReviewers_Call) RunAndReturn(run func(context1 context.Context, getPullRequestReviewersArgs git.GetPullRequestReviewersArgs) (*[]git.IdentityRefWithVote, error)) *Client_GetPullRequestReviewers_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetPullRequestStatus provides a mock function for the type Client
-func (_mock *Client) GetPullRequestStatus(context1 context.Context, getPullRequestStatusArgs git.GetPullRequestStatusArgs) (*git.GitPullRequestStatus, error) {
- ret := _mock.Called(context1, getPullRequestStatusArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetPullRequestStatus")
- }
-
- var r0 *git.GitPullRequestStatus
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetPullRequestStatusArgs) (*git.GitPullRequestStatus, error)); ok {
- return returnFunc(context1, getPullRequestStatusArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetPullRequestStatusArgs) *git.GitPullRequestStatus); ok {
- r0 = returnFunc(context1, getPullRequestStatusArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*git.GitPullRequestStatus)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetPullRequestStatusArgs) error); ok {
- r1 = returnFunc(context1, getPullRequestStatusArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetPullRequestStatus_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetPullRequestStatus'
-type Client_GetPullRequestStatus_Call struct {
- *mock.Call
-}
-
-// GetPullRequestStatus is a helper method to define mock.On call
-// - context1
-// - getPullRequestStatusArgs
-func (_e *Client_Expecter) GetPullRequestStatus(context1 interface{}, getPullRequestStatusArgs interface{}) *Client_GetPullRequestStatus_Call {
- return &Client_GetPullRequestStatus_Call{Call: _e.mock.On("GetPullRequestStatus", context1, getPullRequestStatusArgs)}
-}
-
-func (_c *Client_GetPullRequestStatus_Call) Run(run func(context1 context.Context, getPullRequestStatusArgs git.GetPullRequestStatusArgs)) *Client_GetPullRequestStatus_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetPullRequestStatusArgs))
- })
- return _c
-}
-
-func (_c *Client_GetPullRequestStatus_Call) Return(gitPullRequestStatus *git.GitPullRequestStatus, err error) *Client_GetPullRequestStatus_Call {
- _c.Call.Return(gitPullRequestStatus, err)
- return _c
-}
-
-func (_c *Client_GetPullRequestStatus_Call) RunAndReturn(run func(context1 context.Context, getPullRequestStatusArgs git.GetPullRequestStatusArgs) (*git.GitPullRequestStatus, error)) *Client_GetPullRequestStatus_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetPullRequestStatuses provides a mock function for the type Client
-func (_mock *Client) GetPullRequestStatuses(context1 context.Context, getPullRequestStatusesArgs git.GetPullRequestStatusesArgs) (*[]git.GitPullRequestStatus, error) {
- ret := _mock.Called(context1, getPullRequestStatusesArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetPullRequestStatuses")
- }
-
- var r0 *[]git.GitPullRequestStatus
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetPullRequestStatusesArgs) (*[]git.GitPullRequestStatus, error)); ok {
- return returnFunc(context1, getPullRequestStatusesArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetPullRequestStatusesArgs) *[]git.GitPullRequestStatus); ok {
- r0 = returnFunc(context1, getPullRequestStatusesArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*[]git.GitPullRequestStatus)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetPullRequestStatusesArgs) error); ok {
- r1 = returnFunc(context1, getPullRequestStatusesArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetPullRequestStatuses_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetPullRequestStatuses'
-type Client_GetPullRequestStatuses_Call struct {
- *mock.Call
-}
-
-// GetPullRequestStatuses is a helper method to define mock.On call
-// - context1
-// - getPullRequestStatusesArgs
-func (_e *Client_Expecter) GetPullRequestStatuses(context1 interface{}, getPullRequestStatusesArgs interface{}) *Client_GetPullRequestStatuses_Call {
- return &Client_GetPullRequestStatuses_Call{Call: _e.mock.On("GetPullRequestStatuses", context1, getPullRequestStatusesArgs)}
-}
-
-func (_c *Client_GetPullRequestStatuses_Call) Run(run func(context1 context.Context, getPullRequestStatusesArgs git.GetPullRequestStatusesArgs)) *Client_GetPullRequestStatuses_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetPullRequestStatusesArgs))
- })
- return _c
-}
-
-func (_c *Client_GetPullRequestStatuses_Call) Return(gitPullRequestStatuss *[]git.GitPullRequestStatus, err error) *Client_GetPullRequestStatuses_Call {
- _c.Call.Return(gitPullRequestStatuss, err)
- return _c
-}
-
-func (_c *Client_GetPullRequestStatuses_Call) RunAndReturn(run func(context1 context.Context, getPullRequestStatusesArgs git.GetPullRequestStatusesArgs) (*[]git.GitPullRequestStatus, error)) *Client_GetPullRequestStatuses_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetPullRequestThread provides a mock function for the type Client
-func (_mock *Client) GetPullRequestThread(context1 context.Context, getPullRequestThreadArgs git.GetPullRequestThreadArgs) (*git.GitPullRequestCommentThread, error) {
- ret := _mock.Called(context1, getPullRequestThreadArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetPullRequestThread")
- }
-
- var r0 *git.GitPullRequestCommentThread
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetPullRequestThreadArgs) (*git.GitPullRequestCommentThread, error)); ok {
- return returnFunc(context1, getPullRequestThreadArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetPullRequestThreadArgs) *git.GitPullRequestCommentThread); ok {
- r0 = returnFunc(context1, getPullRequestThreadArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*git.GitPullRequestCommentThread)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetPullRequestThreadArgs) error); ok {
- r1 = returnFunc(context1, getPullRequestThreadArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetPullRequestThread_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetPullRequestThread'
-type Client_GetPullRequestThread_Call struct {
- *mock.Call
-}
-
-// GetPullRequestThread is a helper method to define mock.On call
-// - context1
-// - getPullRequestThreadArgs
-func (_e *Client_Expecter) GetPullRequestThread(context1 interface{}, getPullRequestThreadArgs interface{}) *Client_GetPullRequestThread_Call {
- return &Client_GetPullRequestThread_Call{Call: _e.mock.On("GetPullRequestThread", context1, getPullRequestThreadArgs)}
-}
-
-func (_c *Client_GetPullRequestThread_Call) Run(run func(context1 context.Context, getPullRequestThreadArgs git.GetPullRequestThreadArgs)) *Client_GetPullRequestThread_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetPullRequestThreadArgs))
- })
- return _c
-}
-
-func (_c *Client_GetPullRequestThread_Call) Return(gitPullRequestCommentThread *git.GitPullRequestCommentThread, err error) *Client_GetPullRequestThread_Call {
- _c.Call.Return(gitPullRequestCommentThread, err)
- return _c
-}
-
-func (_c *Client_GetPullRequestThread_Call) RunAndReturn(run func(context1 context.Context, getPullRequestThreadArgs git.GetPullRequestThreadArgs) (*git.GitPullRequestCommentThread, error)) *Client_GetPullRequestThread_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetPullRequestWorkItemRefs provides a mock function for the type Client
-func (_mock *Client) GetPullRequestWorkItemRefs(context1 context.Context, getPullRequestWorkItemRefsArgs git.GetPullRequestWorkItemRefsArgs) (*[]webapi.ResourceRef, error) {
- ret := _mock.Called(context1, getPullRequestWorkItemRefsArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetPullRequestWorkItemRefs")
- }
-
- var r0 *[]webapi.ResourceRef
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetPullRequestWorkItemRefsArgs) (*[]webapi.ResourceRef, error)); ok {
- return returnFunc(context1, getPullRequestWorkItemRefsArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetPullRequestWorkItemRefsArgs) *[]webapi.ResourceRef); ok {
- r0 = returnFunc(context1, getPullRequestWorkItemRefsArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*[]webapi.ResourceRef)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetPullRequestWorkItemRefsArgs) error); ok {
- r1 = returnFunc(context1, getPullRequestWorkItemRefsArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetPullRequestWorkItemRefs_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetPullRequestWorkItemRefs'
-type Client_GetPullRequestWorkItemRefs_Call struct {
- *mock.Call
-}
-
-// GetPullRequestWorkItemRefs is a helper method to define mock.On call
-// - context1
-// - getPullRequestWorkItemRefsArgs
-func (_e *Client_Expecter) GetPullRequestWorkItemRefs(context1 interface{}, getPullRequestWorkItemRefsArgs interface{}) *Client_GetPullRequestWorkItemRefs_Call {
- return &Client_GetPullRequestWorkItemRefs_Call{Call: _e.mock.On("GetPullRequestWorkItemRefs", context1, getPullRequestWorkItemRefsArgs)}
-}
-
-func (_c *Client_GetPullRequestWorkItemRefs_Call) Run(run func(context1 context.Context, getPullRequestWorkItemRefsArgs git.GetPullRequestWorkItemRefsArgs)) *Client_GetPullRequestWorkItemRefs_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetPullRequestWorkItemRefsArgs))
- })
- return _c
-}
-
-func (_c *Client_GetPullRequestWorkItemRefs_Call) Return(resourceRefs *[]webapi.ResourceRef, err error) *Client_GetPullRequestWorkItemRefs_Call {
- _c.Call.Return(resourceRefs, err)
- return _c
-}
-
-func (_c *Client_GetPullRequestWorkItemRefs_Call) RunAndReturn(run func(context1 context.Context, getPullRequestWorkItemRefsArgs git.GetPullRequestWorkItemRefsArgs) (*[]webapi.ResourceRef, error)) *Client_GetPullRequestWorkItemRefs_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetPullRequests provides a mock function for the type Client
-func (_mock *Client) GetPullRequests(context1 context.Context, getPullRequestsArgs git.GetPullRequestsArgs) (*[]git.GitPullRequest, error) {
- ret := _mock.Called(context1, getPullRequestsArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetPullRequests")
- }
-
- var r0 *[]git.GitPullRequest
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetPullRequestsArgs) (*[]git.GitPullRequest, error)); ok {
- return returnFunc(context1, getPullRequestsArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetPullRequestsArgs) *[]git.GitPullRequest); ok {
- r0 = returnFunc(context1, getPullRequestsArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*[]git.GitPullRequest)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetPullRequestsArgs) error); ok {
- r1 = returnFunc(context1, getPullRequestsArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetPullRequests_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetPullRequests'
-type Client_GetPullRequests_Call struct {
- *mock.Call
-}
-
-// GetPullRequests is a helper method to define mock.On call
-// - context1
-// - getPullRequestsArgs
-func (_e *Client_Expecter) GetPullRequests(context1 interface{}, getPullRequestsArgs interface{}) *Client_GetPullRequests_Call {
- return &Client_GetPullRequests_Call{Call: _e.mock.On("GetPullRequests", context1, getPullRequestsArgs)}
-}
-
-func (_c *Client_GetPullRequests_Call) Run(run func(context1 context.Context, getPullRequestsArgs git.GetPullRequestsArgs)) *Client_GetPullRequests_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetPullRequestsArgs))
- })
- return _c
-}
-
-func (_c *Client_GetPullRequests_Call) Return(gitPullRequests *[]git.GitPullRequest, err error) *Client_GetPullRequests_Call {
- _c.Call.Return(gitPullRequests, err)
- return _c
-}
-
-func (_c *Client_GetPullRequests_Call) RunAndReturn(run func(context1 context.Context, getPullRequestsArgs git.GetPullRequestsArgs) (*[]git.GitPullRequest, error)) *Client_GetPullRequests_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetPullRequestsByProject provides a mock function for the type Client
-func (_mock *Client) GetPullRequestsByProject(context1 context.Context, getPullRequestsByProjectArgs git.GetPullRequestsByProjectArgs) (*[]git.GitPullRequest, error) {
- ret := _mock.Called(context1, getPullRequestsByProjectArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetPullRequestsByProject")
- }
-
- var r0 *[]git.GitPullRequest
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetPullRequestsByProjectArgs) (*[]git.GitPullRequest, error)); ok {
- return returnFunc(context1, getPullRequestsByProjectArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetPullRequestsByProjectArgs) *[]git.GitPullRequest); ok {
- r0 = returnFunc(context1, getPullRequestsByProjectArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*[]git.GitPullRequest)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetPullRequestsByProjectArgs) error); ok {
- r1 = returnFunc(context1, getPullRequestsByProjectArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetPullRequestsByProject_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetPullRequestsByProject'
-type Client_GetPullRequestsByProject_Call struct {
- *mock.Call
-}
-
-// GetPullRequestsByProject is a helper method to define mock.On call
-// - context1
-// - getPullRequestsByProjectArgs
-func (_e *Client_Expecter) GetPullRequestsByProject(context1 interface{}, getPullRequestsByProjectArgs interface{}) *Client_GetPullRequestsByProject_Call {
- return &Client_GetPullRequestsByProject_Call{Call: _e.mock.On("GetPullRequestsByProject", context1, getPullRequestsByProjectArgs)}
-}
-
-func (_c *Client_GetPullRequestsByProject_Call) Run(run func(context1 context.Context, getPullRequestsByProjectArgs git.GetPullRequestsByProjectArgs)) *Client_GetPullRequestsByProject_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetPullRequestsByProjectArgs))
- })
- return _c
-}
-
-func (_c *Client_GetPullRequestsByProject_Call) Return(gitPullRequests *[]git.GitPullRequest, err error) *Client_GetPullRequestsByProject_Call {
- _c.Call.Return(gitPullRequests, err)
- return _c
-}
-
-func (_c *Client_GetPullRequestsByProject_Call) RunAndReturn(run func(context1 context.Context, getPullRequestsByProjectArgs git.GetPullRequestsByProjectArgs) (*[]git.GitPullRequest, error)) *Client_GetPullRequestsByProject_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetPush provides a mock function for the type Client
-func (_mock *Client) GetPush(context1 context.Context, getPushArgs git.GetPushArgs) (*git.GitPush, error) {
- ret := _mock.Called(context1, getPushArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetPush")
- }
-
- var r0 *git.GitPush
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetPushArgs) (*git.GitPush, error)); ok {
- return returnFunc(context1, getPushArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetPushArgs) *git.GitPush); ok {
- r0 = returnFunc(context1, getPushArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*git.GitPush)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetPushArgs) error); ok {
- r1 = returnFunc(context1, getPushArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetPush_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetPush'
-type Client_GetPush_Call struct {
- *mock.Call
-}
-
-// GetPush is a helper method to define mock.On call
-// - context1
-// - getPushArgs
-func (_e *Client_Expecter) GetPush(context1 interface{}, getPushArgs interface{}) *Client_GetPush_Call {
- return &Client_GetPush_Call{Call: _e.mock.On("GetPush", context1, getPushArgs)}
-}
-
-func (_c *Client_GetPush_Call) Run(run func(context1 context.Context, getPushArgs git.GetPushArgs)) *Client_GetPush_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetPushArgs))
- })
- return _c
-}
-
-func (_c *Client_GetPush_Call) Return(gitPush *git.GitPush, err error) *Client_GetPush_Call {
- _c.Call.Return(gitPush, err)
- return _c
-}
-
-func (_c *Client_GetPush_Call) RunAndReturn(run func(context1 context.Context, getPushArgs git.GetPushArgs) (*git.GitPush, error)) *Client_GetPush_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetPushCommits provides a mock function for the type Client
-func (_mock *Client) GetPushCommits(context1 context.Context, getPushCommitsArgs git.GetPushCommitsArgs) (*[]git.GitCommitRef, error) {
- ret := _mock.Called(context1, getPushCommitsArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetPushCommits")
- }
-
- var r0 *[]git.GitCommitRef
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetPushCommitsArgs) (*[]git.GitCommitRef, error)); ok {
- return returnFunc(context1, getPushCommitsArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetPushCommitsArgs) *[]git.GitCommitRef); ok {
- r0 = returnFunc(context1, getPushCommitsArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*[]git.GitCommitRef)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetPushCommitsArgs) error); ok {
- r1 = returnFunc(context1, getPushCommitsArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetPushCommits_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetPushCommits'
-type Client_GetPushCommits_Call struct {
- *mock.Call
-}
-
-// GetPushCommits is a helper method to define mock.On call
-// - context1
-// - getPushCommitsArgs
-func (_e *Client_Expecter) GetPushCommits(context1 interface{}, getPushCommitsArgs interface{}) *Client_GetPushCommits_Call {
- return &Client_GetPushCommits_Call{Call: _e.mock.On("GetPushCommits", context1, getPushCommitsArgs)}
-}
-
-func (_c *Client_GetPushCommits_Call) Run(run func(context1 context.Context, getPushCommitsArgs git.GetPushCommitsArgs)) *Client_GetPushCommits_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetPushCommitsArgs))
- })
- return _c
-}
-
-func (_c *Client_GetPushCommits_Call) Return(gitCommitRefs *[]git.GitCommitRef, err error) *Client_GetPushCommits_Call {
- _c.Call.Return(gitCommitRefs, err)
- return _c
-}
-
-func (_c *Client_GetPushCommits_Call) RunAndReturn(run func(context1 context.Context, getPushCommitsArgs git.GetPushCommitsArgs) (*[]git.GitCommitRef, error)) *Client_GetPushCommits_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetPushes provides a mock function for the type Client
-func (_mock *Client) GetPushes(context1 context.Context, getPushesArgs git.GetPushesArgs) (*[]git.GitPush, error) {
- ret := _mock.Called(context1, getPushesArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetPushes")
- }
-
- var r0 *[]git.GitPush
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetPushesArgs) (*[]git.GitPush, error)); ok {
- return returnFunc(context1, getPushesArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetPushesArgs) *[]git.GitPush); ok {
- r0 = returnFunc(context1, getPushesArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*[]git.GitPush)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetPushesArgs) error); ok {
- r1 = returnFunc(context1, getPushesArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetPushes_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetPushes'
-type Client_GetPushes_Call struct {
- *mock.Call
-}
-
-// GetPushes is a helper method to define mock.On call
-// - context1
-// - getPushesArgs
-func (_e *Client_Expecter) GetPushes(context1 interface{}, getPushesArgs interface{}) *Client_GetPushes_Call {
- return &Client_GetPushes_Call{Call: _e.mock.On("GetPushes", context1, getPushesArgs)}
-}
-
-func (_c *Client_GetPushes_Call) Run(run func(context1 context.Context, getPushesArgs git.GetPushesArgs)) *Client_GetPushes_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetPushesArgs))
- })
- return _c
-}
-
-func (_c *Client_GetPushes_Call) Return(gitPushs *[]git.GitPush, err error) *Client_GetPushes_Call {
- _c.Call.Return(gitPushs, err)
- return _c
-}
-
-func (_c *Client_GetPushes_Call) RunAndReturn(run func(context1 context.Context, getPushesArgs git.GetPushesArgs) (*[]git.GitPush, error)) *Client_GetPushes_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetRecycleBinRepositories provides a mock function for the type Client
-func (_mock *Client) GetRecycleBinRepositories(context1 context.Context, getRecycleBinRepositoriesArgs git.GetRecycleBinRepositoriesArgs) (*[]git.GitDeletedRepository, error) {
- ret := _mock.Called(context1, getRecycleBinRepositoriesArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetRecycleBinRepositories")
- }
-
- var r0 *[]git.GitDeletedRepository
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetRecycleBinRepositoriesArgs) (*[]git.GitDeletedRepository, error)); ok {
- return returnFunc(context1, getRecycleBinRepositoriesArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetRecycleBinRepositoriesArgs) *[]git.GitDeletedRepository); ok {
- r0 = returnFunc(context1, getRecycleBinRepositoriesArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*[]git.GitDeletedRepository)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetRecycleBinRepositoriesArgs) error); ok {
- r1 = returnFunc(context1, getRecycleBinRepositoriesArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetRecycleBinRepositories_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetRecycleBinRepositories'
-type Client_GetRecycleBinRepositories_Call struct {
- *mock.Call
-}
-
-// GetRecycleBinRepositories is a helper method to define mock.On call
-// - context1
-// - getRecycleBinRepositoriesArgs
-func (_e *Client_Expecter) GetRecycleBinRepositories(context1 interface{}, getRecycleBinRepositoriesArgs interface{}) *Client_GetRecycleBinRepositories_Call {
- return &Client_GetRecycleBinRepositories_Call{Call: _e.mock.On("GetRecycleBinRepositories", context1, getRecycleBinRepositoriesArgs)}
-}
-
-func (_c *Client_GetRecycleBinRepositories_Call) Run(run func(context1 context.Context, getRecycleBinRepositoriesArgs git.GetRecycleBinRepositoriesArgs)) *Client_GetRecycleBinRepositories_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetRecycleBinRepositoriesArgs))
- })
- return _c
-}
-
-func (_c *Client_GetRecycleBinRepositories_Call) Return(gitDeletedRepositorys *[]git.GitDeletedRepository, err error) *Client_GetRecycleBinRepositories_Call {
- _c.Call.Return(gitDeletedRepositorys, err)
- return _c
-}
-
-func (_c *Client_GetRecycleBinRepositories_Call) RunAndReturn(run func(context1 context.Context, getRecycleBinRepositoriesArgs git.GetRecycleBinRepositoriesArgs) (*[]git.GitDeletedRepository, error)) *Client_GetRecycleBinRepositories_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetRefFavorite provides a mock function for the type Client
-func (_mock *Client) GetRefFavorite(context1 context.Context, getRefFavoriteArgs git.GetRefFavoriteArgs) (*git.GitRefFavorite, error) {
- ret := _mock.Called(context1, getRefFavoriteArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetRefFavorite")
- }
-
- var r0 *git.GitRefFavorite
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetRefFavoriteArgs) (*git.GitRefFavorite, error)); ok {
- return returnFunc(context1, getRefFavoriteArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetRefFavoriteArgs) *git.GitRefFavorite); ok {
- r0 = returnFunc(context1, getRefFavoriteArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*git.GitRefFavorite)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetRefFavoriteArgs) error); ok {
- r1 = returnFunc(context1, getRefFavoriteArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetRefFavorite_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetRefFavorite'
-type Client_GetRefFavorite_Call struct {
- *mock.Call
-}
-
-// GetRefFavorite is a helper method to define mock.On call
-// - context1
-// - getRefFavoriteArgs
-func (_e *Client_Expecter) GetRefFavorite(context1 interface{}, getRefFavoriteArgs interface{}) *Client_GetRefFavorite_Call {
- return &Client_GetRefFavorite_Call{Call: _e.mock.On("GetRefFavorite", context1, getRefFavoriteArgs)}
-}
-
-func (_c *Client_GetRefFavorite_Call) Run(run func(context1 context.Context, getRefFavoriteArgs git.GetRefFavoriteArgs)) *Client_GetRefFavorite_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetRefFavoriteArgs))
- })
- return _c
-}
-
-func (_c *Client_GetRefFavorite_Call) Return(gitRefFavorite *git.GitRefFavorite, err error) *Client_GetRefFavorite_Call {
- _c.Call.Return(gitRefFavorite, err)
- return _c
-}
-
-func (_c *Client_GetRefFavorite_Call) RunAndReturn(run func(context1 context.Context, getRefFavoriteArgs git.GetRefFavoriteArgs) (*git.GitRefFavorite, error)) *Client_GetRefFavorite_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetRefFavorites provides a mock function for the type Client
-func (_mock *Client) GetRefFavorites(context1 context.Context, getRefFavoritesArgs git.GetRefFavoritesArgs) (*[]git.GitRefFavorite, error) {
- ret := _mock.Called(context1, getRefFavoritesArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetRefFavorites")
- }
-
- var r0 *[]git.GitRefFavorite
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetRefFavoritesArgs) (*[]git.GitRefFavorite, error)); ok {
- return returnFunc(context1, getRefFavoritesArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetRefFavoritesArgs) *[]git.GitRefFavorite); ok {
- r0 = returnFunc(context1, getRefFavoritesArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*[]git.GitRefFavorite)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetRefFavoritesArgs) error); ok {
- r1 = returnFunc(context1, getRefFavoritesArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetRefFavorites_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetRefFavorites'
-type Client_GetRefFavorites_Call struct {
- *mock.Call
-}
-
-// GetRefFavorites is a helper method to define mock.On call
-// - context1
-// - getRefFavoritesArgs
-func (_e *Client_Expecter) GetRefFavorites(context1 interface{}, getRefFavoritesArgs interface{}) *Client_GetRefFavorites_Call {
- return &Client_GetRefFavorites_Call{Call: _e.mock.On("GetRefFavorites", context1, getRefFavoritesArgs)}
-}
-
-func (_c *Client_GetRefFavorites_Call) Run(run func(context1 context.Context, getRefFavoritesArgs git.GetRefFavoritesArgs)) *Client_GetRefFavorites_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetRefFavoritesArgs))
- })
- return _c
-}
-
-func (_c *Client_GetRefFavorites_Call) Return(gitRefFavorites *[]git.GitRefFavorite, err error) *Client_GetRefFavorites_Call {
- _c.Call.Return(gitRefFavorites, err)
- return _c
-}
-
-func (_c *Client_GetRefFavorites_Call) RunAndReturn(run func(context1 context.Context, getRefFavoritesArgs git.GetRefFavoritesArgs) (*[]git.GitRefFavorite, error)) *Client_GetRefFavorites_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetRefs provides a mock function for the type Client
-func (_mock *Client) GetRefs(context1 context.Context, getRefsArgs git.GetRefsArgs) (*git.GetRefsResponseValue, error) {
- ret := _mock.Called(context1, getRefsArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetRefs")
- }
-
- var r0 *git.GetRefsResponseValue
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetRefsArgs) (*git.GetRefsResponseValue, error)); ok {
- return returnFunc(context1, getRefsArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetRefsArgs) *git.GetRefsResponseValue); ok {
- r0 = returnFunc(context1, getRefsArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*git.GetRefsResponseValue)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetRefsArgs) error); ok {
- r1 = returnFunc(context1, getRefsArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetRefs_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetRefs'
-type Client_GetRefs_Call struct {
- *mock.Call
-}
-
-// GetRefs is a helper method to define mock.On call
-// - context1
-// - getRefsArgs
-func (_e *Client_Expecter) GetRefs(context1 interface{}, getRefsArgs interface{}) *Client_GetRefs_Call {
- return &Client_GetRefs_Call{Call: _e.mock.On("GetRefs", context1, getRefsArgs)}
-}
-
-func (_c *Client_GetRefs_Call) Run(run func(context1 context.Context, getRefsArgs git.GetRefsArgs)) *Client_GetRefs_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetRefsArgs))
- })
- return _c
-}
-
-func (_c *Client_GetRefs_Call) Return(getRefsResponseValue *git.GetRefsResponseValue, err error) *Client_GetRefs_Call {
- _c.Call.Return(getRefsResponseValue, err)
- return _c
-}
-
-func (_c *Client_GetRefs_Call) RunAndReturn(run func(context1 context.Context, getRefsArgs git.GetRefsArgs) (*git.GetRefsResponseValue, error)) *Client_GetRefs_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetRepositories provides a mock function for the type Client
-func (_mock *Client) GetRepositories(context1 context.Context, getRepositoriesArgs git.GetRepositoriesArgs) (*[]git.GitRepository, error) {
- ret := _mock.Called(context1, getRepositoriesArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetRepositories")
- }
-
- var r0 *[]git.GitRepository
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetRepositoriesArgs) (*[]git.GitRepository, error)); ok {
- return returnFunc(context1, getRepositoriesArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetRepositoriesArgs) *[]git.GitRepository); ok {
- r0 = returnFunc(context1, getRepositoriesArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*[]git.GitRepository)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetRepositoriesArgs) error); ok {
- r1 = returnFunc(context1, getRepositoriesArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetRepositories_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetRepositories'
-type Client_GetRepositories_Call struct {
- *mock.Call
-}
-
-// GetRepositories is a helper method to define mock.On call
-// - context1
-// - getRepositoriesArgs
-func (_e *Client_Expecter) GetRepositories(context1 interface{}, getRepositoriesArgs interface{}) *Client_GetRepositories_Call {
- return &Client_GetRepositories_Call{Call: _e.mock.On("GetRepositories", context1, getRepositoriesArgs)}
-}
-
-func (_c *Client_GetRepositories_Call) Run(run func(context1 context.Context, getRepositoriesArgs git.GetRepositoriesArgs)) *Client_GetRepositories_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetRepositoriesArgs))
- })
- return _c
-}
-
-func (_c *Client_GetRepositories_Call) Return(gitRepositorys *[]git.GitRepository, err error) *Client_GetRepositories_Call {
- _c.Call.Return(gitRepositorys, err)
- return _c
-}
-
-func (_c *Client_GetRepositories_Call) RunAndReturn(run func(context1 context.Context, getRepositoriesArgs git.GetRepositoriesArgs) (*[]git.GitRepository, error)) *Client_GetRepositories_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetRepository provides a mock function for the type Client
-func (_mock *Client) GetRepository(context1 context.Context, getRepositoryArgs git.GetRepositoryArgs) (*git.GitRepository, error) {
- ret := _mock.Called(context1, getRepositoryArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetRepository")
- }
-
- var r0 *git.GitRepository
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetRepositoryArgs) (*git.GitRepository, error)); ok {
- return returnFunc(context1, getRepositoryArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetRepositoryArgs) *git.GitRepository); ok {
- r0 = returnFunc(context1, getRepositoryArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*git.GitRepository)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetRepositoryArgs) error); ok {
- r1 = returnFunc(context1, getRepositoryArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetRepository_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetRepository'
-type Client_GetRepository_Call struct {
- *mock.Call
-}
-
-// GetRepository is a helper method to define mock.On call
-// - context1
-// - getRepositoryArgs
-func (_e *Client_Expecter) GetRepository(context1 interface{}, getRepositoryArgs interface{}) *Client_GetRepository_Call {
- return &Client_GetRepository_Call{Call: _e.mock.On("GetRepository", context1, getRepositoryArgs)}
-}
-
-func (_c *Client_GetRepository_Call) Run(run func(context1 context.Context, getRepositoryArgs git.GetRepositoryArgs)) *Client_GetRepository_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetRepositoryArgs))
- })
- return _c
-}
-
-func (_c *Client_GetRepository_Call) Return(gitRepository *git.GitRepository, err error) *Client_GetRepository_Call {
- _c.Call.Return(gitRepository, err)
- return _c
-}
-
-func (_c *Client_GetRepository_Call) RunAndReturn(run func(context1 context.Context, getRepositoryArgs git.GetRepositoryArgs) (*git.GitRepository, error)) *Client_GetRepository_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetRepositoryWithParent provides a mock function for the type Client
-func (_mock *Client) GetRepositoryWithParent(context1 context.Context, getRepositoryWithParentArgs git.GetRepositoryWithParentArgs) (*git.GitRepository, error) {
- ret := _mock.Called(context1, getRepositoryWithParentArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetRepositoryWithParent")
- }
-
- var r0 *git.GitRepository
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetRepositoryWithParentArgs) (*git.GitRepository, error)); ok {
- return returnFunc(context1, getRepositoryWithParentArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetRepositoryWithParentArgs) *git.GitRepository); ok {
- r0 = returnFunc(context1, getRepositoryWithParentArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*git.GitRepository)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetRepositoryWithParentArgs) error); ok {
- r1 = returnFunc(context1, getRepositoryWithParentArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetRepositoryWithParent_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetRepositoryWithParent'
-type Client_GetRepositoryWithParent_Call struct {
- *mock.Call
-}
-
-// GetRepositoryWithParent is a helper method to define mock.On call
-// - context1
-// - getRepositoryWithParentArgs
-func (_e *Client_Expecter) GetRepositoryWithParent(context1 interface{}, getRepositoryWithParentArgs interface{}) *Client_GetRepositoryWithParent_Call {
- return &Client_GetRepositoryWithParent_Call{Call: _e.mock.On("GetRepositoryWithParent", context1, getRepositoryWithParentArgs)}
-}
-
-func (_c *Client_GetRepositoryWithParent_Call) Run(run func(context1 context.Context, getRepositoryWithParentArgs git.GetRepositoryWithParentArgs)) *Client_GetRepositoryWithParent_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetRepositoryWithParentArgs))
- })
- return _c
-}
-
-func (_c *Client_GetRepositoryWithParent_Call) Return(gitRepository *git.GitRepository, err error) *Client_GetRepositoryWithParent_Call {
- _c.Call.Return(gitRepository, err)
- return _c
-}
-
-func (_c *Client_GetRepositoryWithParent_Call) RunAndReturn(run func(context1 context.Context, getRepositoryWithParentArgs git.GetRepositoryWithParentArgs) (*git.GitRepository, error)) *Client_GetRepositoryWithParent_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetRevert provides a mock function for the type Client
-func (_mock *Client) GetRevert(context1 context.Context, getRevertArgs git.GetRevertArgs) (*git.GitRevert, error) {
- ret := _mock.Called(context1, getRevertArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetRevert")
- }
-
- var r0 *git.GitRevert
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetRevertArgs) (*git.GitRevert, error)); ok {
- return returnFunc(context1, getRevertArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetRevertArgs) *git.GitRevert); ok {
- r0 = returnFunc(context1, getRevertArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*git.GitRevert)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetRevertArgs) error); ok {
- r1 = returnFunc(context1, getRevertArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetRevert_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetRevert'
-type Client_GetRevert_Call struct {
- *mock.Call
-}
-
-// GetRevert is a helper method to define mock.On call
-// - context1
-// - getRevertArgs
-func (_e *Client_Expecter) GetRevert(context1 interface{}, getRevertArgs interface{}) *Client_GetRevert_Call {
- return &Client_GetRevert_Call{Call: _e.mock.On("GetRevert", context1, getRevertArgs)}
-}
-
-func (_c *Client_GetRevert_Call) Run(run func(context1 context.Context, getRevertArgs git.GetRevertArgs)) *Client_GetRevert_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetRevertArgs))
- })
- return _c
-}
-
-func (_c *Client_GetRevert_Call) Return(gitRevert *git.GitRevert, err error) *Client_GetRevert_Call {
- _c.Call.Return(gitRevert, err)
- return _c
-}
-
-func (_c *Client_GetRevert_Call) RunAndReturn(run func(context1 context.Context, getRevertArgs git.GetRevertArgs) (*git.GitRevert, error)) *Client_GetRevert_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetRevertForRefName provides a mock function for the type Client
-func (_mock *Client) GetRevertForRefName(context1 context.Context, getRevertForRefNameArgs git.GetRevertForRefNameArgs) (*git.GitRevert, error) {
- ret := _mock.Called(context1, getRevertForRefNameArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetRevertForRefName")
- }
-
- var r0 *git.GitRevert
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetRevertForRefNameArgs) (*git.GitRevert, error)); ok {
- return returnFunc(context1, getRevertForRefNameArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetRevertForRefNameArgs) *git.GitRevert); ok {
- r0 = returnFunc(context1, getRevertForRefNameArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*git.GitRevert)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetRevertForRefNameArgs) error); ok {
- r1 = returnFunc(context1, getRevertForRefNameArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetRevertForRefName_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetRevertForRefName'
-type Client_GetRevertForRefName_Call struct {
- *mock.Call
-}
-
-// GetRevertForRefName is a helper method to define mock.On call
-// - context1
-// - getRevertForRefNameArgs
-func (_e *Client_Expecter) GetRevertForRefName(context1 interface{}, getRevertForRefNameArgs interface{}) *Client_GetRevertForRefName_Call {
- return &Client_GetRevertForRefName_Call{Call: _e.mock.On("GetRevertForRefName", context1, getRevertForRefNameArgs)}
-}
-
-func (_c *Client_GetRevertForRefName_Call) Run(run func(context1 context.Context, getRevertForRefNameArgs git.GetRevertForRefNameArgs)) *Client_GetRevertForRefName_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetRevertForRefNameArgs))
- })
- return _c
-}
-
-func (_c *Client_GetRevertForRefName_Call) Return(gitRevert *git.GitRevert, err error) *Client_GetRevertForRefName_Call {
- _c.Call.Return(gitRevert, err)
- return _c
-}
-
-func (_c *Client_GetRevertForRefName_Call) RunAndReturn(run func(context1 context.Context, getRevertForRefNameArgs git.GetRevertForRefNameArgs) (*git.GitRevert, error)) *Client_GetRevertForRefName_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetStatuses provides a mock function for the type Client
-func (_mock *Client) GetStatuses(context1 context.Context, getStatusesArgs git.GetStatusesArgs) (*[]git.GitStatus, error) {
- ret := _mock.Called(context1, getStatusesArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetStatuses")
- }
-
- var r0 *[]git.GitStatus
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetStatusesArgs) (*[]git.GitStatus, error)); ok {
- return returnFunc(context1, getStatusesArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetStatusesArgs) *[]git.GitStatus); ok {
- r0 = returnFunc(context1, getStatusesArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*[]git.GitStatus)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetStatusesArgs) error); ok {
- r1 = returnFunc(context1, getStatusesArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetStatuses_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetStatuses'
-type Client_GetStatuses_Call struct {
- *mock.Call
-}
-
-// GetStatuses is a helper method to define mock.On call
-// - context1
-// - getStatusesArgs
-func (_e *Client_Expecter) GetStatuses(context1 interface{}, getStatusesArgs interface{}) *Client_GetStatuses_Call {
- return &Client_GetStatuses_Call{Call: _e.mock.On("GetStatuses", context1, getStatusesArgs)}
-}
-
-func (_c *Client_GetStatuses_Call) Run(run func(context1 context.Context, getStatusesArgs git.GetStatusesArgs)) *Client_GetStatuses_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetStatusesArgs))
- })
- return _c
-}
-
-func (_c *Client_GetStatuses_Call) Return(gitStatuss *[]git.GitStatus, err error) *Client_GetStatuses_Call {
- _c.Call.Return(gitStatuss, err)
- return _c
-}
-
-func (_c *Client_GetStatuses_Call) RunAndReturn(run func(context1 context.Context, getStatusesArgs git.GetStatusesArgs) (*[]git.GitStatus, error)) *Client_GetStatuses_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetSuggestions provides a mock function for the type Client
-func (_mock *Client) GetSuggestions(context1 context.Context, getSuggestionsArgs git.GetSuggestionsArgs) (*[]git.GitSuggestion, error) {
- ret := _mock.Called(context1, getSuggestionsArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetSuggestions")
- }
-
- var r0 *[]git.GitSuggestion
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetSuggestionsArgs) (*[]git.GitSuggestion, error)); ok {
- return returnFunc(context1, getSuggestionsArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetSuggestionsArgs) *[]git.GitSuggestion); ok {
- r0 = returnFunc(context1, getSuggestionsArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*[]git.GitSuggestion)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetSuggestionsArgs) error); ok {
- r1 = returnFunc(context1, getSuggestionsArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetSuggestions_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetSuggestions'
-type Client_GetSuggestions_Call struct {
- *mock.Call
-}
-
-// GetSuggestions is a helper method to define mock.On call
-// - context1
-// - getSuggestionsArgs
-func (_e *Client_Expecter) GetSuggestions(context1 interface{}, getSuggestionsArgs interface{}) *Client_GetSuggestions_Call {
- return &Client_GetSuggestions_Call{Call: _e.mock.On("GetSuggestions", context1, getSuggestionsArgs)}
-}
-
-func (_c *Client_GetSuggestions_Call) Run(run func(context1 context.Context, getSuggestionsArgs git.GetSuggestionsArgs)) *Client_GetSuggestions_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetSuggestionsArgs))
- })
- return _c
-}
-
-func (_c *Client_GetSuggestions_Call) Return(gitSuggestions *[]git.GitSuggestion, err error) *Client_GetSuggestions_Call {
- _c.Call.Return(gitSuggestions, err)
- return _c
-}
-
-func (_c *Client_GetSuggestions_Call) RunAndReturn(run func(context1 context.Context, getSuggestionsArgs git.GetSuggestionsArgs) (*[]git.GitSuggestion, error)) *Client_GetSuggestions_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetThreads provides a mock function for the type Client
-func (_mock *Client) GetThreads(context1 context.Context, getThreadsArgs git.GetThreadsArgs) (*[]git.GitPullRequestCommentThread, error) {
- ret := _mock.Called(context1, getThreadsArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetThreads")
- }
-
- var r0 *[]git.GitPullRequestCommentThread
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetThreadsArgs) (*[]git.GitPullRequestCommentThread, error)); ok {
- return returnFunc(context1, getThreadsArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetThreadsArgs) *[]git.GitPullRequestCommentThread); ok {
- r0 = returnFunc(context1, getThreadsArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*[]git.GitPullRequestCommentThread)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetThreadsArgs) error); ok {
- r1 = returnFunc(context1, getThreadsArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetThreads_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetThreads'
-type Client_GetThreads_Call struct {
- *mock.Call
-}
-
-// GetThreads is a helper method to define mock.On call
-// - context1
-// - getThreadsArgs
-func (_e *Client_Expecter) GetThreads(context1 interface{}, getThreadsArgs interface{}) *Client_GetThreads_Call {
- return &Client_GetThreads_Call{Call: _e.mock.On("GetThreads", context1, getThreadsArgs)}
-}
-
-func (_c *Client_GetThreads_Call) Run(run func(context1 context.Context, getThreadsArgs git.GetThreadsArgs)) *Client_GetThreads_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetThreadsArgs))
- })
- return _c
-}
-
-func (_c *Client_GetThreads_Call) Return(gitPullRequestCommentThreads *[]git.GitPullRequestCommentThread, err error) *Client_GetThreads_Call {
- _c.Call.Return(gitPullRequestCommentThreads, err)
- return _c
-}
-
-func (_c *Client_GetThreads_Call) RunAndReturn(run func(context1 context.Context, getThreadsArgs git.GetThreadsArgs) (*[]git.GitPullRequestCommentThread, error)) *Client_GetThreads_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetTree provides a mock function for the type Client
-func (_mock *Client) GetTree(context1 context.Context, getTreeArgs git.GetTreeArgs) (*git.GitTreeRef, error) {
- ret := _mock.Called(context1, getTreeArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetTree")
- }
-
- var r0 *git.GitTreeRef
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetTreeArgs) (*git.GitTreeRef, error)); ok {
- return returnFunc(context1, getTreeArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetTreeArgs) *git.GitTreeRef); ok {
- r0 = returnFunc(context1, getTreeArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*git.GitTreeRef)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetTreeArgs) error); ok {
- r1 = returnFunc(context1, getTreeArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetTree_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetTree'
-type Client_GetTree_Call struct {
- *mock.Call
-}
-
-// GetTree is a helper method to define mock.On call
-// - context1
-// - getTreeArgs
-func (_e *Client_Expecter) GetTree(context1 interface{}, getTreeArgs interface{}) *Client_GetTree_Call {
- return &Client_GetTree_Call{Call: _e.mock.On("GetTree", context1, getTreeArgs)}
-}
-
-func (_c *Client_GetTree_Call) Run(run func(context1 context.Context, getTreeArgs git.GetTreeArgs)) *Client_GetTree_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetTreeArgs))
- })
- return _c
-}
-
-func (_c *Client_GetTree_Call) Return(gitTreeRef *git.GitTreeRef, err error) *Client_GetTree_Call {
- _c.Call.Return(gitTreeRef, err)
- return _c
-}
-
-func (_c *Client_GetTree_Call) RunAndReturn(run func(context1 context.Context, getTreeArgs git.GetTreeArgs) (*git.GitTreeRef, error)) *Client_GetTree_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetTreeZip provides a mock function for the type Client
-func (_mock *Client) GetTreeZip(context1 context.Context, getTreeZipArgs git.GetTreeZipArgs) (io.ReadCloser, error) {
- ret := _mock.Called(context1, getTreeZipArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetTreeZip")
- }
-
- var r0 io.ReadCloser
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetTreeZipArgs) (io.ReadCloser, error)); ok {
- return returnFunc(context1, getTreeZipArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.GetTreeZipArgs) io.ReadCloser); ok {
- r0 = returnFunc(context1, getTreeZipArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(io.ReadCloser)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.GetTreeZipArgs) error); ok {
- r1 = returnFunc(context1, getTreeZipArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_GetTreeZip_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetTreeZip'
-type Client_GetTreeZip_Call struct {
- *mock.Call
-}
-
-// GetTreeZip is a helper method to define mock.On call
-// - context1
-// - getTreeZipArgs
-func (_e *Client_Expecter) GetTreeZip(context1 interface{}, getTreeZipArgs interface{}) *Client_GetTreeZip_Call {
- return &Client_GetTreeZip_Call{Call: _e.mock.On("GetTreeZip", context1, getTreeZipArgs)}
-}
-
-func (_c *Client_GetTreeZip_Call) Run(run func(context1 context.Context, getTreeZipArgs git.GetTreeZipArgs)) *Client_GetTreeZip_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.GetTreeZipArgs))
- })
- return _c
-}
-
-func (_c *Client_GetTreeZip_Call) Return(readCloser io.ReadCloser, err error) *Client_GetTreeZip_Call {
- _c.Call.Return(readCloser, err)
- return _c
-}
-
-func (_c *Client_GetTreeZip_Call) RunAndReturn(run func(context1 context.Context, getTreeZipArgs git.GetTreeZipArgs) (io.ReadCloser, error)) *Client_GetTreeZip_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// QueryImportRequests provides a mock function for the type Client
-func (_mock *Client) QueryImportRequests(context1 context.Context, queryImportRequestsArgs git.QueryImportRequestsArgs) (*[]git.GitImportRequest, error) {
- ret := _mock.Called(context1, queryImportRequestsArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for QueryImportRequests")
- }
-
- var r0 *[]git.GitImportRequest
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.QueryImportRequestsArgs) (*[]git.GitImportRequest, error)); ok {
- return returnFunc(context1, queryImportRequestsArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.QueryImportRequestsArgs) *[]git.GitImportRequest); ok {
- r0 = returnFunc(context1, queryImportRequestsArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*[]git.GitImportRequest)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.QueryImportRequestsArgs) error); ok {
- r1 = returnFunc(context1, queryImportRequestsArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_QueryImportRequests_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'QueryImportRequests'
-type Client_QueryImportRequests_Call struct {
- *mock.Call
-}
-
-// QueryImportRequests is a helper method to define mock.On call
-// - context1
-// - queryImportRequestsArgs
-func (_e *Client_Expecter) QueryImportRequests(context1 interface{}, queryImportRequestsArgs interface{}) *Client_QueryImportRequests_Call {
- return &Client_QueryImportRequests_Call{Call: _e.mock.On("QueryImportRequests", context1, queryImportRequestsArgs)}
-}
-
-func (_c *Client_QueryImportRequests_Call) Run(run func(context1 context.Context, queryImportRequestsArgs git.QueryImportRequestsArgs)) *Client_QueryImportRequests_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.QueryImportRequestsArgs))
- })
- return _c
-}
-
-func (_c *Client_QueryImportRequests_Call) Return(gitImportRequests *[]git.GitImportRequest, err error) *Client_QueryImportRequests_Call {
- _c.Call.Return(gitImportRequests, err)
- return _c
-}
-
-func (_c *Client_QueryImportRequests_Call) RunAndReturn(run func(context1 context.Context, queryImportRequestsArgs git.QueryImportRequestsArgs) (*[]git.GitImportRequest, error)) *Client_QueryImportRequests_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// RestoreRepositoryFromRecycleBin provides a mock function for the type Client
-func (_mock *Client) RestoreRepositoryFromRecycleBin(context1 context.Context, restoreRepositoryFromRecycleBinArgs git.RestoreRepositoryFromRecycleBinArgs) (*git.GitRepository, error) {
- ret := _mock.Called(context1, restoreRepositoryFromRecycleBinArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for RestoreRepositoryFromRecycleBin")
- }
-
- var r0 *git.GitRepository
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.RestoreRepositoryFromRecycleBinArgs) (*git.GitRepository, error)); ok {
- return returnFunc(context1, restoreRepositoryFromRecycleBinArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.RestoreRepositoryFromRecycleBinArgs) *git.GitRepository); ok {
- r0 = returnFunc(context1, restoreRepositoryFromRecycleBinArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*git.GitRepository)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.RestoreRepositoryFromRecycleBinArgs) error); ok {
- r1 = returnFunc(context1, restoreRepositoryFromRecycleBinArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_RestoreRepositoryFromRecycleBin_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RestoreRepositoryFromRecycleBin'
-type Client_RestoreRepositoryFromRecycleBin_Call struct {
- *mock.Call
-}
-
-// RestoreRepositoryFromRecycleBin is a helper method to define mock.On call
-// - context1
-// - restoreRepositoryFromRecycleBinArgs
-func (_e *Client_Expecter) RestoreRepositoryFromRecycleBin(context1 interface{}, restoreRepositoryFromRecycleBinArgs interface{}) *Client_RestoreRepositoryFromRecycleBin_Call {
- return &Client_RestoreRepositoryFromRecycleBin_Call{Call: _e.mock.On("RestoreRepositoryFromRecycleBin", context1, restoreRepositoryFromRecycleBinArgs)}
-}
-
-func (_c *Client_RestoreRepositoryFromRecycleBin_Call) Run(run func(context1 context.Context, restoreRepositoryFromRecycleBinArgs git.RestoreRepositoryFromRecycleBinArgs)) *Client_RestoreRepositoryFromRecycleBin_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.RestoreRepositoryFromRecycleBinArgs))
- })
- return _c
-}
-
-func (_c *Client_RestoreRepositoryFromRecycleBin_Call) Return(gitRepository *git.GitRepository, err error) *Client_RestoreRepositoryFromRecycleBin_Call {
- _c.Call.Return(gitRepository, err)
- return _c
-}
-
-func (_c *Client_RestoreRepositoryFromRecycleBin_Call) RunAndReturn(run func(context1 context.Context, restoreRepositoryFromRecycleBinArgs git.RestoreRepositoryFromRecycleBinArgs) (*git.GitRepository, error)) *Client_RestoreRepositoryFromRecycleBin_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// SharePullRequest provides a mock function for the type Client
-func (_mock *Client) SharePullRequest(context1 context.Context, sharePullRequestArgs git.SharePullRequestArgs) error {
- ret := _mock.Called(context1, sharePullRequestArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for SharePullRequest")
- }
-
- var r0 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.SharePullRequestArgs) error); ok {
- r0 = returnFunc(context1, sharePullRequestArgs)
- } else {
- r0 = ret.Error(0)
- }
- return r0
-}
-
-// Client_SharePullRequest_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SharePullRequest'
-type Client_SharePullRequest_Call struct {
- *mock.Call
-}
-
-// SharePullRequest is a helper method to define mock.On call
-// - context1
-// - sharePullRequestArgs
-func (_e *Client_Expecter) SharePullRequest(context1 interface{}, sharePullRequestArgs interface{}) *Client_SharePullRequest_Call {
- return &Client_SharePullRequest_Call{Call: _e.mock.On("SharePullRequest", context1, sharePullRequestArgs)}
-}
-
-func (_c *Client_SharePullRequest_Call) Run(run func(context1 context.Context, sharePullRequestArgs git.SharePullRequestArgs)) *Client_SharePullRequest_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.SharePullRequestArgs))
- })
- return _c
-}
-
-func (_c *Client_SharePullRequest_Call) Return(err error) *Client_SharePullRequest_Call {
- _c.Call.Return(err)
- return _c
-}
-
-func (_c *Client_SharePullRequest_Call) RunAndReturn(run func(context1 context.Context, sharePullRequestArgs git.SharePullRequestArgs) error) *Client_SharePullRequest_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// UpdateComment provides a mock function for the type Client
-func (_mock *Client) UpdateComment(context1 context.Context, updateCommentArgs git.UpdateCommentArgs) (*git.Comment, error) {
- ret := _mock.Called(context1, updateCommentArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for UpdateComment")
- }
-
- var r0 *git.Comment
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.UpdateCommentArgs) (*git.Comment, error)); ok {
- return returnFunc(context1, updateCommentArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.UpdateCommentArgs) *git.Comment); ok {
- r0 = returnFunc(context1, updateCommentArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*git.Comment)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.UpdateCommentArgs) error); ok {
- r1 = returnFunc(context1, updateCommentArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_UpdateComment_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UpdateComment'
-type Client_UpdateComment_Call struct {
- *mock.Call
-}
-
-// UpdateComment is a helper method to define mock.On call
-// - context1
-// - updateCommentArgs
-func (_e *Client_Expecter) UpdateComment(context1 interface{}, updateCommentArgs interface{}) *Client_UpdateComment_Call {
- return &Client_UpdateComment_Call{Call: _e.mock.On("UpdateComment", context1, updateCommentArgs)}
-}
-
-func (_c *Client_UpdateComment_Call) Run(run func(context1 context.Context, updateCommentArgs git.UpdateCommentArgs)) *Client_UpdateComment_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.UpdateCommentArgs))
- })
- return _c
-}
-
-func (_c *Client_UpdateComment_Call) Return(comment *git.Comment, err error) *Client_UpdateComment_Call {
- _c.Call.Return(comment, err)
- return _c
-}
-
-func (_c *Client_UpdateComment_Call) RunAndReturn(run func(context1 context.Context, updateCommentArgs git.UpdateCommentArgs) (*git.Comment, error)) *Client_UpdateComment_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// UpdateImportRequest provides a mock function for the type Client
-func (_mock *Client) UpdateImportRequest(context1 context.Context, updateImportRequestArgs git.UpdateImportRequestArgs) (*git.GitImportRequest, error) {
- ret := _mock.Called(context1, updateImportRequestArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for UpdateImportRequest")
- }
-
- var r0 *git.GitImportRequest
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.UpdateImportRequestArgs) (*git.GitImportRequest, error)); ok {
- return returnFunc(context1, updateImportRequestArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.UpdateImportRequestArgs) *git.GitImportRequest); ok {
- r0 = returnFunc(context1, updateImportRequestArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*git.GitImportRequest)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.UpdateImportRequestArgs) error); ok {
- r1 = returnFunc(context1, updateImportRequestArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_UpdateImportRequest_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UpdateImportRequest'
-type Client_UpdateImportRequest_Call struct {
- *mock.Call
-}
-
-// UpdateImportRequest is a helper method to define mock.On call
-// - context1
-// - updateImportRequestArgs
-func (_e *Client_Expecter) UpdateImportRequest(context1 interface{}, updateImportRequestArgs interface{}) *Client_UpdateImportRequest_Call {
- return &Client_UpdateImportRequest_Call{Call: _e.mock.On("UpdateImportRequest", context1, updateImportRequestArgs)}
-}
-
-func (_c *Client_UpdateImportRequest_Call) Run(run func(context1 context.Context, updateImportRequestArgs git.UpdateImportRequestArgs)) *Client_UpdateImportRequest_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.UpdateImportRequestArgs))
- })
- return _c
-}
-
-func (_c *Client_UpdateImportRequest_Call) Return(gitImportRequest *git.GitImportRequest, err error) *Client_UpdateImportRequest_Call {
- _c.Call.Return(gitImportRequest, err)
- return _c
-}
-
-func (_c *Client_UpdateImportRequest_Call) RunAndReturn(run func(context1 context.Context, updateImportRequestArgs git.UpdateImportRequestArgs) (*git.GitImportRequest, error)) *Client_UpdateImportRequest_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// UpdatePullRequest provides a mock function for the type Client
-func (_mock *Client) UpdatePullRequest(context1 context.Context, updatePullRequestArgs git.UpdatePullRequestArgs) (*git.GitPullRequest, error) {
- ret := _mock.Called(context1, updatePullRequestArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for UpdatePullRequest")
- }
-
- var r0 *git.GitPullRequest
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.UpdatePullRequestArgs) (*git.GitPullRequest, error)); ok {
- return returnFunc(context1, updatePullRequestArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.UpdatePullRequestArgs) *git.GitPullRequest); ok {
- r0 = returnFunc(context1, updatePullRequestArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*git.GitPullRequest)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.UpdatePullRequestArgs) error); ok {
- r1 = returnFunc(context1, updatePullRequestArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_UpdatePullRequest_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UpdatePullRequest'
-type Client_UpdatePullRequest_Call struct {
- *mock.Call
-}
-
-// UpdatePullRequest is a helper method to define mock.On call
-// - context1
-// - updatePullRequestArgs
-func (_e *Client_Expecter) UpdatePullRequest(context1 interface{}, updatePullRequestArgs interface{}) *Client_UpdatePullRequest_Call {
- return &Client_UpdatePullRequest_Call{Call: _e.mock.On("UpdatePullRequest", context1, updatePullRequestArgs)}
-}
-
-func (_c *Client_UpdatePullRequest_Call) Run(run func(context1 context.Context, updatePullRequestArgs git.UpdatePullRequestArgs)) *Client_UpdatePullRequest_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.UpdatePullRequestArgs))
- })
- return _c
-}
-
-func (_c *Client_UpdatePullRequest_Call) Return(gitPullRequest *git.GitPullRequest, err error) *Client_UpdatePullRequest_Call {
- _c.Call.Return(gitPullRequest, err)
- return _c
-}
-
-func (_c *Client_UpdatePullRequest_Call) RunAndReturn(run func(context1 context.Context, updatePullRequestArgs git.UpdatePullRequestArgs) (*git.GitPullRequest, error)) *Client_UpdatePullRequest_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// UpdatePullRequestIterationStatuses provides a mock function for the type Client
-func (_mock *Client) UpdatePullRequestIterationStatuses(context1 context.Context, updatePullRequestIterationStatusesArgs git.UpdatePullRequestIterationStatusesArgs) error {
- ret := _mock.Called(context1, updatePullRequestIterationStatusesArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for UpdatePullRequestIterationStatuses")
- }
-
- var r0 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.UpdatePullRequestIterationStatusesArgs) error); ok {
- r0 = returnFunc(context1, updatePullRequestIterationStatusesArgs)
- } else {
- r0 = ret.Error(0)
- }
- return r0
-}
-
-// Client_UpdatePullRequestIterationStatuses_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UpdatePullRequestIterationStatuses'
-type Client_UpdatePullRequestIterationStatuses_Call struct {
- *mock.Call
-}
-
-// UpdatePullRequestIterationStatuses is a helper method to define mock.On call
-// - context1
-// - updatePullRequestIterationStatusesArgs
-func (_e *Client_Expecter) UpdatePullRequestIterationStatuses(context1 interface{}, updatePullRequestIterationStatusesArgs interface{}) *Client_UpdatePullRequestIterationStatuses_Call {
- return &Client_UpdatePullRequestIterationStatuses_Call{Call: _e.mock.On("UpdatePullRequestIterationStatuses", context1, updatePullRequestIterationStatusesArgs)}
-}
-
-func (_c *Client_UpdatePullRequestIterationStatuses_Call) Run(run func(context1 context.Context, updatePullRequestIterationStatusesArgs git.UpdatePullRequestIterationStatusesArgs)) *Client_UpdatePullRequestIterationStatuses_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.UpdatePullRequestIterationStatusesArgs))
- })
- return _c
-}
-
-func (_c *Client_UpdatePullRequestIterationStatuses_Call) Return(err error) *Client_UpdatePullRequestIterationStatuses_Call {
- _c.Call.Return(err)
- return _c
-}
-
-func (_c *Client_UpdatePullRequestIterationStatuses_Call) RunAndReturn(run func(context1 context.Context, updatePullRequestIterationStatusesArgs git.UpdatePullRequestIterationStatusesArgs) error) *Client_UpdatePullRequestIterationStatuses_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// UpdatePullRequestProperties provides a mock function for the type Client
-func (_mock *Client) UpdatePullRequestProperties(context1 context.Context, updatePullRequestPropertiesArgs git.UpdatePullRequestPropertiesArgs) (interface{}, error) {
- ret := _mock.Called(context1, updatePullRequestPropertiesArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for UpdatePullRequestProperties")
- }
-
- var r0 interface{}
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.UpdatePullRequestPropertiesArgs) (interface{}, error)); ok {
- return returnFunc(context1, updatePullRequestPropertiesArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.UpdatePullRequestPropertiesArgs) interface{}); ok {
- r0 = returnFunc(context1, updatePullRequestPropertiesArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(interface{})
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.UpdatePullRequestPropertiesArgs) error); ok {
- r1 = returnFunc(context1, updatePullRequestPropertiesArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_UpdatePullRequestProperties_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UpdatePullRequestProperties'
-type Client_UpdatePullRequestProperties_Call struct {
- *mock.Call
-}
-
-// UpdatePullRequestProperties is a helper method to define mock.On call
-// - context1
-// - updatePullRequestPropertiesArgs
-func (_e *Client_Expecter) UpdatePullRequestProperties(context1 interface{}, updatePullRequestPropertiesArgs interface{}) *Client_UpdatePullRequestProperties_Call {
- return &Client_UpdatePullRequestProperties_Call{Call: _e.mock.On("UpdatePullRequestProperties", context1, updatePullRequestPropertiesArgs)}
-}
-
-func (_c *Client_UpdatePullRequestProperties_Call) Run(run func(context1 context.Context, updatePullRequestPropertiesArgs git.UpdatePullRequestPropertiesArgs)) *Client_UpdatePullRequestProperties_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.UpdatePullRequestPropertiesArgs))
- })
- return _c
-}
-
-func (_c *Client_UpdatePullRequestProperties_Call) Return(ifaceVal interface{}, err error) *Client_UpdatePullRequestProperties_Call {
- _c.Call.Return(ifaceVal, err)
- return _c
-}
-
-func (_c *Client_UpdatePullRequestProperties_Call) RunAndReturn(run func(context1 context.Context, updatePullRequestPropertiesArgs git.UpdatePullRequestPropertiesArgs) (interface{}, error)) *Client_UpdatePullRequestProperties_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// UpdatePullRequestReviewer provides a mock function for the type Client
-func (_mock *Client) UpdatePullRequestReviewer(context1 context.Context, updatePullRequestReviewerArgs git.UpdatePullRequestReviewerArgs) (*git.IdentityRefWithVote, error) {
- ret := _mock.Called(context1, updatePullRequestReviewerArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for UpdatePullRequestReviewer")
- }
-
- var r0 *git.IdentityRefWithVote
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.UpdatePullRequestReviewerArgs) (*git.IdentityRefWithVote, error)); ok {
- return returnFunc(context1, updatePullRequestReviewerArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.UpdatePullRequestReviewerArgs) *git.IdentityRefWithVote); ok {
- r0 = returnFunc(context1, updatePullRequestReviewerArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*git.IdentityRefWithVote)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.UpdatePullRequestReviewerArgs) error); ok {
- r1 = returnFunc(context1, updatePullRequestReviewerArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_UpdatePullRequestReviewer_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UpdatePullRequestReviewer'
-type Client_UpdatePullRequestReviewer_Call struct {
- *mock.Call
-}
-
-// UpdatePullRequestReviewer is a helper method to define mock.On call
-// - context1
-// - updatePullRequestReviewerArgs
-func (_e *Client_Expecter) UpdatePullRequestReviewer(context1 interface{}, updatePullRequestReviewerArgs interface{}) *Client_UpdatePullRequestReviewer_Call {
- return &Client_UpdatePullRequestReviewer_Call{Call: _e.mock.On("UpdatePullRequestReviewer", context1, updatePullRequestReviewerArgs)}
-}
-
-func (_c *Client_UpdatePullRequestReviewer_Call) Run(run func(context1 context.Context, updatePullRequestReviewerArgs git.UpdatePullRequestReviewerArgs)) *Client_UpdatePullRequestReviewer_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.UpdatePullRequestReviewerArgs))
- })
- return _c
-}
-
-func (_c *Client_UpdatePullRequestReviewer_Call) Return(identityRefWithVote *git.IdentityRefWithVote, err error) *Client_UpdatePullRequestReviewer_Call {
- _c.Call.Return(identityRefWithVote, err)
- return _c
-}
-
-func (_c *Client_UpdatePullRequestReviewer_Call) RunAndReturn(run func(context1 context.Context, updatePullRequestReviewerArgs git.UpdatePullRequestReviewerArgs) (*git.IdentityRefWithVote, error)) *Client_UpdatePullRequestReviewer_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// UpdatePullRequestReviewers provides a mock function for the type Client
-func (_mock *Client) UpdatePullRequestReviewers(context1 context.Context, updatePullRequestReviewersArgs git.UpdatePullRequestReviewersArgs) error {
- ret := _mock.Called(context1, updatePullRequestReviewersArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for UpdatePullRequestReviewers")
- }
-
- var r0 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.UpdatePullRequestReviewersArgs) error); ok {
- r0 = returnFunc(context1, updatePullRequestReviewersArgs)
- } else {
- r0 = ret.Error(0)
- }
- return r0
-}
-
-// Client_UpdatePullRequestReviewers_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UpdatePullRequestReviewers'
-type Client_UpdatePullRequestReviewers_Call struct {
- *mock.Call
-}
-
-// UpdatePullRequestReviewers is a helper method to define mock.On call
-// - context1
-// - updatePullRequestReviewersArgs
-func (_e *Client_Expecter) UpdatePullRequestReviewers(context1 interface{}, updatePullRequestReviewersArgs interface{}) *Client_UpdatePullRequestReviewers_Call {
- return &Client_UpdatePullRequestReviewers_Call{Call: _e.mock.On("UpdatePullRequestReviewers", context1, updatePullRequestReviewersArgs)}
-}
-
-func (_c *Client_UpdatePullRequestReviewers_Call) Run(run func(context1 context.Context, updatePullRequestReviewersArgs git.UpdatePullRequestReviewersArgs)) *Client_UpdatePullRequestReviewers_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.UpdatePullRequestReviewersArgs))
- })
- return _c
-}
-
-func (_c *Client_UpdatePullRequestReviewers_Call) Return(err error) *Client_UpdatePullRequestReviewers_Call {
- _c.Call.Return(err)
- return _c
-}
-
-func (_c *Client_UpdatePullRequestReviewers_Call) RunAndReturn(run func(context1 context.Context, updatePullRequestReviewersArgs git.UpdatePullRequestReviewersArgs) error) *Client_UpdatePullRequestReviewers_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// UpdatePullRequestStatuses provides a mock function for the type Client
-func (_mock *Client) UpdatePullRequestStatuses(context1 context.Context, updatePullRequestStatusesArgs git.UpdatePullRequestStatusesArgs) error {
- ret := _mock.Called(context1, updatePullRequestStatusesArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for UpdatePullRequestStatuses")
- }
-
- var r0 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.UpdatePullRequestStatusesArgs) error); ok {
- r0 = returnFunc(context1, updatePullRequestStatusesArgs)
- } else {
- r0 = ret.Error(0)
- }
- return r0
-}
-
-// Client_UpdatePullRequestStatuses_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UpdatePullRequestStatuses'
-type Client_UpdatePullRequestStatuses_Call struct {
- *mock.Call
-}
-
-// UpdatePullRequestStatuses is a helper method to define mock.On call
-// - context1
-// - updatePullRequestStatusesArgs
-func (_e *Client_Expecter) UpdatePullRequestStatuses(context1 interface{}, updatePullRequestStatusesArgs interface{}) *Client_UpdatePullRequestStatuses_Call {
- return &Client_UpdatePullRequestStatuses_Call{Call: _e.mock.On("UpdatePullRequestStatuses", context1, updatePullRequestStatusesArgs)}
-}
-
-func (_c *Client_UpdatePullRequestStatuses_Call) Run(run func(context1 context.Context, updatePullRequestStatusesArgs git.UpdatePullRequestStatusesArgs)) *Client_UpdatePullRequestStatuses_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.UpdatePullRequestStatusesArgs))
- })
- return _c
-}
-
-func (_c *Client_UpdatePullRequestStatuses_Call) Return(err error) *Client_UpdatePullRequestStatuses_Call {
- _c.Call.Return(err)
- return _c
-}
-
-func (_c *Client_UpdatePullRequestStatuses_Call) RunAndReturn(run func(context1 context.Context, updatePullRequestStatusesArgs git.UpdatePullRequestStatusesArgs) error) *Client_UpdatePullRequestStatuses_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// UpdateRef provides a mock function for the type Client
-func (_mock *Client) UpdateRef(context1 context.Context, updateRefArgs git.UpdateRefArgs) (*git.GitRef, error) {
- ret := _mock.Called(context1, updateRefArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for UpdateRef")
- }
-
- var r0 *git.GitRef
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.UpdateRefArgs) (*git.GitRef, error)); ok {
- return returnFunc(context1, updateRefArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.UpdateRefArgs) *git.GitRef); ok {
- r0 = returnFunc(context1, updateRefArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*git.GitRef)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.UpdateRefArgs) error); ok {
- r1 = returnFunc(context1, updateRefArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_UpdateRef_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UpdateRef'
-type Client_UpdateRef_Call struct {
- *mock.Call
-}
-
-// UpdateRef is a helper method to define mock.On call
-// - context1
-// - updateRefArgs
-func (_e *Client_Expecter) UpdateRef(context1 interface{}, updateRefArgs interface{}) *Client_UpdateRef_Call {
- return &Client_UpdateRef_Call{Call: _e.mock.On("UpdateRef", context1, updateRefArgs)}
-}
-
-func (_c *Client_UpdateRef_Call) Run(run func(context1 context.Context, updateRefArgs git.UpdateRefArgs)) *Client_UpdateRef_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.UpdateRefArgs))
- })
- return _c
-}
-
-func (_c *Client_UpdateRef_Call) Return(gitRef *git.GitRef, err error) *Client_UpdateRef_Call {
- _c.Call.Return(gitRef, err)
- return _c
-}
-
-func (_c *Client_UpdateRef_Call) RunAndReturn(run func(context1 context.Context, updateRefArgs git.UpdateRefArgs) (*git.GitRef, error)) *Client_UpdateRef_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// UpdateRefs provides a mock function for the type Client
-func (_mock *Client) UpdateRefs(context1 context.Context, updateRefsArgs git.UpdateRefsArgs) (*[]git.GitRefUpdateResult, error) {
- ret := _mock.Called(context1, updateRefsArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for UpdateRefs")
- }
-
- var r0 *[]git.GitRefUpdateResult
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.UpdateRefsArgs) (*[]git.GitRefUpdateResult, error)); ok {
- return returnFunc(context1, updateRefsArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.UpdateRefsArgs) *[]git.GitRefUpdateResult); ok {
- r0 = returnFunc(context1, updateRefsArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*[]git.GitRefUpdateResult)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.UpdateRefsArgs) error); ok {
- r1 = returnFunc(context1, updateRefsArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_UpdateRefs_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UpdateRefs'
-type Client_UpdateRefs_Call struct {
- *mock.Call
-}
-
-// UpdateRefs is a helper method to define mock.On call
-// - context1
-// - updateRefsArgs
-func (_e *Client_Expecter) UpdateRefs(context1 interface{}, updateRefsArgs interface{}) *Client_UpdateRefs_Call {
- return &Client_UpdateRefs_Call{Call: _e.mock.On("UpdateRefs", context1, updateRefsArgs)}
-}
-
-func (_c *Client_UpdateRefs_Call) Run(run func(context1 context.Context, updateRefsArgs git.UpdateRefsArgs)) *Client_UpdateRefs_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.UpdateRefsArgs))
- })
- return _c
-}
-
-func (_c *Client_UpdateRefs_Call) Return(gitRefUpdateResults *[]git.GitRefUpdateResult, err error) *Client_UpdateRefs_Call {
- _c.Call.Return(gitRefUpdateResults, err)
- return _c
-}
-
-func (_c *Client_UpdateRefs_Call) RunAndReturn(run func(context1 context.Context, updateRefsArgs git.UpdateRefsArgs) (*[]git.GitRefUpdateResult, error)) *Client_UpdateRefs_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// UpdateRepository provides a mock function for the type Client
-func (_mock *Client) UpdateRepository(context1 context.Context, updateRepositoryArgs git.UpdateRepositoryArgs) (*git.GitRepository, error) {
- ret := _mock.Called(context1, updateRepositoryArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for UpdateRepository")
- }
-
- var r0 *git.GitRepository
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.UpdateRepositoryArgs) (*git.GitRepository, error)); ok {
- return returnFunc(context1, updateRepositoryArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.UpdateRepositoryArgs) *git.GitRepository); ok {
- r0 = returnFunc(context1, updateRepositoryArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*git.GitRepository)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.UpdateRepositoryArgs) error); ok {
- r1 = returnFunc(context1, updateRepositoryArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_UpdateRepository_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UpdateRepository'
-type Client_UpdateRepository_Call struct {
- *mock.Call
-}
-
-// UpdateRepository is a helper method to define mock.On call
-// - context1
-// - updateRepositoryArgs
-func (_e *Client_Expecter) UpdateRepository(context1 interface{}, updateRepositoryArgs interface{}) *Client_UpdateRepository_Call {
- return &Client_UpdateRepository_Call{Call: _e.mock.On("UpdateRepository", context1, updateRepositoryArgs)}
-}
-
-func (_c *Client_UpdateRepository_Call) Run(run func(context1 context.Context, updateRepositoryArgs git.UpdateRepositoryArgs)) *Client_UpdateRepository_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.UpdateRepositoryArgs))
- })
- return _c
-}
-
-func (_c *Client_UpdateRepository_Call) Return(gitRepository *git.GitRepository, err error) *Client_UpdateRepository_Call {
- _c.Call.Return(gitRepository, err)
- return _c
-}
-
-func (_c *Client_UpdateRepository_Call) RunAndReturn(run func(context1 context.Context, updateRepositoryArgs git.UpdateRepositoryArgs) (*git.GitRepository, error)) *Client_UpdateRepository_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// UpdateThread provides a mock function for the type Client
-func (_mock *Client) UpdateThread(context1 context.Context, updateThreadArgs git.UpdateThreadArgs) (*git.GitPullRequestCommentThread, error) {
- ret := _mock.Called(context1, updateThreadArgs)
-
- if len(ret) == 0 {
- panic("no return value specified for UpdateThread")
- }
-
- var r0 *git.GitPullRequestCommentThread
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.UpdateThreadArgs) (*git.GitPullRequestCommentThread, error)); ok {
- return returnFunc(context1, updateThreadArgs)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, git.UpdateThreadArgs) *git.GitPullRequestCommentThread); ok {
- r0 = returnFunc(context1, updateThreadArgs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*git.GitPullRequestCommentThread)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, git.UpdateThreadArgs) error); ok {
- r1 = returnFunc(context1, updateThreadArgs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Client_UpdateThread_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UpdateThread'
-type Client_UpdateThread_Call struct {
- *mock.Call
-}
-
-// UpdateThread is a helper method to define mock.On call
-// - context1
-// - updateThreadArgs
-func (_e *Client_Expecter) UpdateThread(context1 interface{}, updateThreadArgs interface{}) *Client_UpdateThread_Call {
- return &Client_UpdateThread_Call{Call: _e.mock.On("UpdateThread", context1, updateThreadArgs)}
-}
-
-func (_c *Client_UpdateThread_Call) Run(run func(context1 context.Context, updateThreadArgs git.UpdateThreadArgs)) *Client_UpdateThread_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context), args[1].(git.UpdateThreadArgs))
- })
- return _c
-}
-
-func (_c *Client_UpdateThread_Call) Return(gitPullRequestCommentThread *git.GitPullRequestCommentThread, err error) *Client_UpdateThread_Call {
- _c.Call.Return(gitPullRequestCommentThread, err)
- return _c
-}
-
-func (_c *Client_UpdateThread_Call) RunAndReturn(run func(context1 context.Context, updateThreadArgs git.UpdateThreadArgs) (*git.GitPullRequestCommentThread, error)) *Client_UpdateThread_Call {
- _c.Call.Return(run)
- return _c
-}
diff --git a/applicationset/services/scm_provider/azure_devops_test.go b/applicationset/services/scm_provider/azure_devops_test.go
index 0b8b914efa..d718802ad3 100644
--- a/applicationset/services/scm_provider/azure_devops_test.go
+++ b/applicationset/services/scm_provider/azure_devops_test.go
@@ -2,7 +2,6 @@ package scm_provider
import (
"context"
- "errors"
"fmt"
"testing"
@@ -12,10 +11,10 @@ import (
"github.com/stretchr/testify/require"
"k8s.io/utils/ptr"
- "github.com/microsoft/azure-devops-go-api/azuredevops/v7"
- azureGit "github.com/microsoft/azure-devops-go-api/azuredevops/v7/git"
+ "github.com/microsoft/azure-devops-go-api/azuredevops"
+ azureGit "github.com/microsoft/azure-devops-go-api/azuredevops/git"
- azureMock "github.com/argoproj/argo-cd/v3/applicationset/services/scm_provider/azure_devops/git/mocks"
+ azureMock "github.com/argoproj/argo-cd/v2/applicationset/services/scm_provider/azure_devops/git/mocks"
)
func s(input string) *string {
@@ -29,7 +28,7 @@ func TestAzureDevopsRepoHasPath(t *testing.T) {
path := "dir/subdir/item.yaml"
branchName := "my/featurebranch"
- ctx := t.Context()
+ ctx := context.Background()
uuid := uuid.New().String()
testCases := []struct {
@@ -42,7 +41,7 @@ func TestAzureDevopsRepoHasPath(t *testing.T) {
}{
{
name: "RepoHasPath when Azure DevOps client factory fails returns error",
- clientError: errors.New("Client factory error"),
+ clientError: fmt.Errorf("Client factory error"),
},
{
name: "RepoHasPath when found returns true",
@@ -63,7 +62,7 @@ func TestAzureDevopsRepoHasPath(t *testing.T) {
{
name: "RepoHasPath when unknown Azure DevOps error occurs returns error",
pathFound: false,
- azureDevopsError: errors.New("Undefined error from Azure Devops"),
+ azureDevopsError: fmt.Errorf("Undefined error from Azure Devops"),
returnError: true,
errorMessage: "failed to check for path existence",
},
@@ -115,7 +114,7 @@ func TestGetDefaultBranchOnDisabledRepo(t *testing.T) {
repoName := "myorg_project_repo"
defaultBranch := "main"
- ctx := t.Context()
+ ctx := context.Background()
testCases := []struct {
name string
@@ -134,7 +133,7 @@ func TestGetDefaultBranchOnDisabledRepo(t *testing.T) {
},
{
name: "other error when calling azure devops returns error",
- azureDevOpsError: errors.New("some unknown error"),
+ azureDevOpsError: fmt.Errorf("some unknown error"),
shouldReturnError: true,
},
}
@@ -174,7 +173,7 @@ func TestGetAllBranchesOnDisabledRepo(t *testing.T) {
repoName := "myorg_project_repo"
defaultBranch := "main"
- ctx := t.Context()
+ ctx := context.Background()
testCases := []struct {
name string
@@ -193,7 +192,7 @@ func TestGetAllBranchesOnDisabledRepo(t *testing.T) {
},
{
name: "other error when calling azure devops returns error",
- azureDevOpsError: errors.New("some unknown error"),
+ azureDevOpsError: fmt.Errorf("some unknown error"),
shouldReturnError: true,
},
}
@@ -233,7 +232,7 @@ func TestAzureDevOpsGetDefaultBranchStripsRefsName(t *testing.T) {
teamProject := "myorg_project"
repoName := "myorg_project_repo"
- ctx := t.Context()
+ ctx := context.Background()
uuid := uuid.New().String()
strippedBranchName := "somebranch"
defaultBranch := fmt.Sprintf("refs/heads/%v", strippedBranchName)
@@ -264,7 +263,7 @@ func TestAzureDevOpsGetBranchesDefultBranchOnly(t *testing.T) {
teamProject := "myorg_project"
repoName := "myorg_project_repo"
- ctx := t.Context()
+ ctx := context.Background()
uuid := uuid.New().String()
defaultBranch := "main"
@@ -272,7 +271,7 @@ func TestAzureDevOpsGetBranchesDefultBranchOnly(t *testing.T) {
testCases := []struct {
name string
expectedBranch *azureGit.GitBranchStats
- getBranchesAPIError error
+ getBranchesApiError error
clientError error
}{
{
@@ -281,11 +280,11 @@ func TestAzureDevOpsGetBranchesDefultBranchOnly(t *testing.T) {
},
{
name: "GetBranches AllBranches false when request fails returns error and empty result",
- getBranchesAPIError: errors.New("Remote Azure Devops GetBranches error"),
+ getBranchesApiError: fmt.Errorf("Remote Azure Devops GetBranches error"),
},
{
name: "GetBranches AllBranches false when Azure DevOps client fails returns error",
- clientError: errors.New("Could not get Azure Devops API client"),
+ clientError: fmt.Errorf("Could not get Azure Devops API client"),
},
{
name: "GetBranches AllBranches false when branch returned with long commit SHA",
@@ -300,7 +299,7 @@ func TestAzureDevOpsGetBranchesDefultBranchOnly(t *testing.T) {
clientFactoryMock := &AzureClientFactoryMock{mock: &mock.Mock{}}
clientFactoryMock.mock.On("GetClient", mock.Anything).Return(&gitClientMock, testCase.clientError)
- gitClientMock.On("GetBranch", ctx, azureGit.GetBranchArgs{RepositoryId: &repoName, Project: &teamProject, Name: &defaultBranch}).Return(testCase.expectedBranch, testCase.getBranchesAPIError)
+ gitClientMock.On("GetBranch", ctx, azureGit.GetBranchArgs{RepositoryId: &repoName, Project: &teamProject, Name: &defaultBranch}).Return(testCase.expectedBranch, testCase.getBranchesApiError)
repo := &Repository{Organization: organization, Repository: repoName, RepositoryId: uuid, Branch: defaultBranch}
@@ -314,9 +313,9 @@ func TestAzureDevOpsGetBranchesDefultBranchOnly(t *testing.T) {
return
}
- if testCase.getBranchesAPIError != nil {
+ if testCase.getBranchesApiError != nil {
assert.Empty(t, branches)
- require.ErrorContains(t, err, testCase.getBranchesAPIError.Error())
+ require.ErrorContains(t, err, testCase.getBranchesApiError.Error())
} else {
if testCase.expectedBranch != nil {
assert.NotEmpty(t, branches)
@@ -335,13 +334,13 @@ func TestAzureDevopsGetBranches(t *testing.T) {
teamProject := "myorg_project"
repoName := "myorg_project_repo"
- ctx := t.Context()
+ ctx := context.Background()
uuid := uuid.New().String()
testCases := []struct {
name string
expectedBranches *[]azureGit.GitBranchStats
- getBranchesAPIError error
+ getBranchesApiError error
clientError error
allBranches bool
expectedProcessingErrorMsg string
@@ -353,7 +352,7 @@ func TestAzureDevopsGetBranches(t *testing.T) {
},
{
name: "GetBranches when Azure DevOps request fails returns error and empty result",
- getBranchesAPIError: errors.New("Remote Azure Devops GetBranches error"),
+ getBranchesApiError: fmt.Errorf("Remote Azure Devops GetBranches error"),
allBranches: true,
},
{
@@ -363,7 +362,7 @@ func TestAzureDevopsGetBranches(t *testing.T) {
},
{
name: "GetBranches when git client retrievel fails returns error",
- clientError: errors.New("Could not get Azure Devops API client"),
+ clientError: fmt.Errorf("Could not get Azure Devops API client"),
allBranches: true,
},
{
@@ -384,7 +383,7 @@ func TestAzureDevopsGetBranches(t *testing.T) {
clientFactoryMock := &AzureClientFactoryMock{mock: &mock.Mock{}}
clientFactoryMock.mock.On("GetClient", mock.Anything).Return(&gitClientMock, testCase.clientError)
- gitClientMock.On("GetBranches", ctx, azureGit.GetBranchesArgs{RepositoryId: &repoName, Project: &teamProject}).Return(testCase.expectedBranches, testCase.getBranchesAPIError)
+ gitClientMock.On("GetBranches", ctx, azureGit.GetBranchesArgs{RepositoryId: &repoName, Project: &teamProject}).Return(testCase.expectedBranches, testCase.getBranchesApiError)
repo := &Repository{Organization: organization, Repository: repoName, RepositoryId: uuid}
@@ -403,9 +402,9 @@ func TestAzureDevopsGetBranches(t *testing.T) {
return
}
- if testCase.getBranchesAPIError != nil {
+ if testCase.getBranchesApiError != nil {
assert.Empty(t, branches)
- require.ErrorContains(t, err, testCase.getBranchesAPIError.Error())
+ require.ErrorContains(t, err, testCase.getBranchesApiError.Error())
} else {
if len(*testCase.expectedBranches) > 0 {
assert.NotEmpty(t, branches)
@@ -427,7 +426,7 @@ func TestGetAzureDevopsRepositories(t *testing.T) {
teamProject := "myorg_project"
uuid := uuid.New()
- ctx := t.Context()
+ ctx := context.Background()
repoId := &uuid
@@ -448,7 +447,7 @@ func TestGetAzureDevopsRepositories(t *testing.T) {
},
{
name: "ListRepos when Azure DevOps request fails returns error",
- getRepositoriesError: errors.New("Could not get repos"),
+ getRepositoriesError: fmt.Errorf("Could not get repos"),
},
{
name: "ListRepos when repo has no name returns empty list",
diff --git a/applicationset/services/scm_provider/bitbucket_cloud.go b/applicationset/services/scm_provider/bitbucket_cloud.go
index 518200855a..4468aee687 100644
--- a/applicationset/services/scm_provider/bitbucket_cloud.go
+++ b/applicationset/services/scm_provider/bitbucket_cloud.go
@@ -2,7 +2,6 @@ package scm_provider
import (
"context"
- "errors"
"fmt"
"net/http"
"strings"
@@ -52,7 +51,7 @@ func (c *ExtendedClient) GetContents(repo *Repository, path string) (bool, error
var _ SCMProviderService = &BitBucketCloudProvider{}
-func NewBitBucketCloudProvider(owner string, user string, password string, allBranches bool) (*BitBucketCloudProvider, error) {
+func NewBitBucketCloudProvider(ctx context.Context, owner string, user string, password string, allBranches bool) (*BitBucketCloudProvider, error) {
client := &ExtendedClient{
bitbucket.NewBasicAuth(user, password),
user,
@@ -62,7 +61,7 @@ func NewBitBucketCloudProvider(owner string, user string, password string, allBr
return &BitBucketCloudProvider{client: client, owner: owner, allBranches: allBranches}, nil
}
-func (g *BitBucketCloudProvider) GetBranches(_ context.Context, repo *Repository) ([]*Repository, error) {
+func (g *BitBucketCloudProvider) GetBranches(ctx context.Context, repo *Repository) ([]*Repository, error) {
repos := []*Repository{}
branches, err := g.listBranches(repo)
if err != nil {
@@ -87,7 +86,7 @@ func (g *BitBucketCloudProvider) GetBranches(_ context.Context, repo *Repository
return repos, nil
}
-func (g *BitBucketCloudProvider) ListRepos(_ context.Context, cloneProtocol string) ([]*Repository, error) {
+func (g *BitBucketCloudProvider) ListRepos(ctx context.Context, cloneProtocol string) ([]*Repository, error) {
if cloneProtocol == "" {
cloneProtocol = "ssh"
}
@@ -101,7 +100,7 @@ func (g *BitBucketCloudProvider) ListRepos(_ context.Context, cloneProtocol stri
return nil, fmt.Errorf("error listing repositories for %s: %w", g.owner, err)
}
for _, bitBucketRepo := range accountReposResp.Items {
- cloneURL, err := findCloneURL(cloneProtocol, &bitBucketRepo)
+ cloneUrl, err := findCloneURL(cloneProtocol, &bitBucketRepo)
if err != nil {
return nil, fmt.Errorf("error fetching clone url for repo %s: %w", bitBucketRepo.Slug, err)
}
@@ -109,7 +108,7 @@ func (g *BitBucketCloudProvider) ListRepos(_ context.Context, cloneProtocol stri
Organization: g.owner,
Repository: bitBucketRepo.Slug,
Branch: bitBucketRepo.Mainbranch.Name,
- URL: *cloneURL,
+ URL: *cloneUrl,
Labels: []string{},
RepositoryId: bitBucketRepo.Uuid,
})
@@ -117,7 +116,7 @@ func (g *BitBucketCloudProvider) ListRepos(_ context.Context, cloneProtocol stri
return repos, nil
}
-func (g *BitBucketCloudProvider) RepoHasPath(_ context.Context, repo *Repository, path string) (bool, error) {
+func (g *BitBucketCloudProvider) RepoHasPath(ctx context.Context, repo *Repository, path string) (bool, error) {
contents, err := g.client.GetContents(repo, path)
if err != nil {
return false, err
@@ -154,19 +153,19 @@ func (g *BitBucketCloudProvider) listBranches(repo *Repository) ([]bitbucket.Rep
}
func findCloneURL(cloneProtocol string, repo *bitbucket.Repository) (*string, error) {
- cloneLinks, ok := repo.Links["clone"].([]any)
+ cloneLinks, ok := repo.Links["clone"].([]interface{})
if !ok {
- return nil, errors.New("unknown type returned from repo links")
+ return nil, fmt.Errorf("unknown type returned from repo links")
}
for _, link := range cloneLinks {
- linkEntry, ok := link.(map[string]any)
+ linkEntry, ok := link.(map[string]interface{})
if !ok {
- return nil, errors.New("unknown type returned from clone link")
+ return nil, fmt.Errorf("unknown type returned from clone link")
}
if linkEntry["name"] == cloneProtocol {
url, ok := linkEntry["href"].(string)
if !ok {
- return nil, errors.New("could not find href for clone link")
+ return nil, fmt.Errorf("could not find href for clone link")
}
return &url, nil
}
diff --git a/applicationset/services/scm_provider/bitbucket_cloud_test.go b/applicationset/services/scm_provider/bitbucket_cloud_test.go
index d9462e46a0..d4127dbbf4 100644
--- a/applicationset/services/scm_provider/bitbucket_cloud_test.go
+++ b/applicationset/services/scm_provider/bitbucket_cloud_test.go
@@ -1,6 +1,7 @@
package scm_provider
import (
+ "context"
"fmt"
"net/http"
"net/http/httptest"
@@ -9,7 +10,7 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
)
func TestBitbucketHasRepo(t *testing.T) {
@@ -86,14 +87,14 @@ func TestBitbucketHasRepo(t *testing.T) {
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
- provider, _ := NewBitBucketCloudProvider(c.owner, "user", "password", false)
+ provider, _ := NewBitBucketCloudProvider(context.Background(), c.owner, "user", "password", false)
repo := &Repository{
Organization: c.owner,
Repository: c.repo,
SHA: c.sha,
Branch: "main",
}
- hasPath, err := provider.RepoHasPath(t.Context(), repo, c.path)
+ hasPath, err := provider.RepoHasPath(context.Background(), repo, c.path)
if err != nil {
require.Error(t, fmt.Errorf("Error in test %w", err))
}
@@ -486,8 +487,8 @@ func TestBitbucketListRepos(t *testing.T) {
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
- provider, _ := NewBitBucketCloudProvider(c.owner, "user", "password", c.allBranches)
- rawRepos, err := ListRepos(t.Context(), provider, c.filters, c.proto)
+ provider, _ := NewBitBucketCloudProvider(context.Background(), c.owner, "user", "password", c.allBranches)
+ rawRepos, err := ListRepos(context.Background(), provider, c.filters, c.proto)
if c.hasError {
require.Error(t, err)
} else {
diff --git a/applicationset/services/scm_provider/bitbucket_server.go b/applicationset/services/scm_provider/bitbucket_server.go
index cbe0c6aad4..79baa727a1 100644
--- a/applicationset/services/scm_provider/bitbucket_server.go
+++ b/applicationset/services/scm_provider/bitbucket_server.go
@@ -10,7 +10,7 @@ import (
bitbucketv1 "github.com/gfleury/go-bitbucket-v1"
log "github.com/sirupsen/logrus"
- "github.com/argoproj/argo-cd/v3/applicationset/utils"
+ "github.com/argoproj/argo-cd/v2/applicationset/utils"
)
type BitbucketServerProvider struct {
@@ -64,7 +64,7 @@ func newBitbucketServerProvider(ctx context.Context, bitbucketConfig *bitbucketv
}
func (b *BitbucketServerProvider) ListRepos(_ context.Context, cloneProtocol string) ([]*Repository, error) {
- paged := map[string]any{
+ paged := map[string]interface{}{
"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]any{
+ opts := map[string]interface{}{
"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]any{
+ paged := map[string]interface{}{
"limit": 100,
}
for {
diff --git a/applicationset/services/scm_provider/bitbucket_server_test.go b/applicationset/services/scm_provider/bitbucket_server_test.go
index 5559eb231c..5b4a957fea 100644
--- a/applicationset/services/scm_provider/bitbucket_server_test.go
+++ b/applicationset/services/scm_provider/bitbucket_server_test.go
@@ -1,6 +1,7 @@
package scm_provider
import (
+ "context"
"crypto/x509"
"encoding/pem"
"io"
@@ -102,9 +103,9 @@ func TestListReposNoAuth(t *testing.T) {
defaultHandler(t)(w, r)
}))
defer ts.Close()
- provider, err := NewBitbucketServerProviderNoAuth(t.Context(), ts.URL, "PROJECT", true, "", false, nil)
+ provider, err := NewBitbucketServerProviderNoAuth(context.Background(), ts.URL, "PROJECT", true, "", false, nil)
require.NoError(t, err)
- repos, err := provider.ListRepos(t.Context(), "ssh")
+ repos, err := provider.ListRepos(context.Background(), "ssh")
verifyDefaultRepo(t, err, repos)
}
@@ -194,9 +195,9 @@ func TestListReposPagination(t *testing.T) {
}
}))
defer ts.Close()
- provider, err := NewBitbucketServerProviderNoAuth(t.Context(), ts.URL, "PROJECT", true, "", false, nil)
+ provider, err := NewBitbucketServerProviderNoAuth(context.Background(), ts.URL, "PROJECT", true, "", false, nil)
require.NoError(t, err)
- repos, err := provider.ListRepos(t.Context(), "ssh")
+ repos, err := provider.ListRepos(context.Background(), "ssh")
require.NoError(t, err)
assert.Len(t, repos, 2)
assert.Equal(t, Repository{
@@ -271,9 +272,9 @@ func TestGetBranchesBranchPagination(t *testing.T) {
defaultHandler(t)(w, r)
}))
defer ts.Close()
- provider, err := NewBitbucketServerProviderNoAuth(t.Context(), ts.URL, "PROJECT", true, "", false, nil)
+ provider, err := NewBitbucketServerProviderNoAuth(context.Background(), ts.URL, "PROJECT", true, "", false, nil)
require.NoError(t, err)
- repos, err := provider.GetBranches(t.Context(), &Repository{
+ repos, err := provider.GetBranches(context.Background(), &Repository{
Organization: "PROJECT",
Repository: "REPO",
URL: "ssh://git@mycompany.bitbucket.org/PROJECT/REPO.git",
@@ -306,7 +307,8 @@ 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"))
- if r.RequestURI == "/rest/api/1.0/projects/PROJECT/repos/REPO/branches/default" {
+ switch r.RequestURI {
+ case "/rest/api/1.0/projects/PROJECT/repos/REPO/branches/default":
_, err := io.WriteString(w, `{
"id": "refs/heads/default",
"displayId": "default",
@@ -323,9 +325,9 @@ func TestGetBranchesDefaultOnly(t *testing.T) {
defaultHandler(t)(w, r)
}))
defer ts.Close()
- provider, err := NewBitbucketServerProviderNoAuth(t.Context(), ts.URL, "PROJECT", false, "", false, nil)
+ provider, err := NewBitbucketServerProviderNoAuth(context.Background(), ts.URL, "PROJECT", false, "", false, nil)
require.NoError(t, err)
- repos, err := provider.GetBranches(t.Context(), &Repository{
+ repos, err := provider.GetBranches(context.Background(), &Repository{
Organization: "PROJECT",
Repository: "REPO",
URL: "ssh://git@mycompany.bitbucket.org/PROJECT/REPO.git",
@@ -348,15 +350,16 @@ 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"))
- if r.RequestURI == "/rest/api/1.0/projects/PROJECT/repos/REPO/branches/default" {
+ switch r.RequestURI {
+ case "/rest/api/1.0/projects/PROJECT/repos/REPO/branches/default":
http.Error(w, "Not found", http.StatusNotFound)
}
defaultHandler(t)(w, r)
}))
defer ts.Close()
- provider, err := NewBitbucketServerProviderNoAuth(t.Context(), ts.URL, "PROJECT", false, "", false, nil)
+ provider, err := NewBitbucketServerProviderNoAuth(context.Background(), ts.URL, "PROJECT", false, "", false, nil)
require.NoError(t, err)
- repos, err := provider.GetBranches(t.Context(), &Repository{
+ repos, err := provider.GetBranches(context.Background(), &Repository{
Organization: "PROJECT",
Repository: "REPO",
URL: "ssh://git@mycompany.bitbucket.org/PROJECT/REPO.git",
@@ -368,16 +371,17 @@ func TestGetBranchesMissingDefault(t *testing.T) {
}
func TestGetBranchesEmptyRepo(t *testing.T) {
- ts := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
+ ts := httptest.NewServer(http.HandlerFunc(func(w 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" {
+ switch r.RequestURI {
+ case "/rest/api/1.0/projects/PROJECT/repos/REPO/branches/default":
return
}
}))
defer ts.Close()
- provider, err := NewBitbucketServerProviderNoAuth(t.Context(), ts.URL, "PROJECT", false, "", false, nil)
+ provider, err := NewBitbucketServerProviderNoAuth(context.Background(), ts.URL, "PROJECT", false, "", false, nil)
require.NoError(t, err)
- repos, err := provider.GetBranches(t.Context(), &Repository{
+ repos, err := provider.GetBranches(context.Background(), &Repository{
Organization: "PROJECT",
Repository: "REPO",
URL: "ssh://git@mycompany.bitbucket.org/PROJECT/REPO.git",
@@ -391,15 +395,16 @@ 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"))
- if r.RequestURI == "/rest/api/1.0/projects/PROJECT/repos/REPO/branches/default" {
+ switch r.RequestURI {
+ case "/rest/api/1.0/projects/PROJECT/repos/REPO/branches/default":
http.Error(w, "Internal server error", http.StatusInternalServerError)
}
defaultHandler(t)(w, r)
}))
defer ts.Close()
- provider, err := NewBitbucketServerProviderNoAuth(t.Context(), ts.URL, "PROJECT", false, "", false, nil)
+ provider, err := NewBitbucketServerProviderNoAuth(context.Background(), ts.URL, "PROJECT", false, "", false, nil)
require.NoError(t, err)
- _, err = provider.GetBranches(t.Context(), &Repository{
+ _, err = provider.GetBranches(context.Background(), &Repository{
Organization: "PROJECT",
Repository: "REPO",
URL: "ssh://git@mycompany.bitbucket.org/PROJECT/REPO.git",
@@ -451,7 +456,7 @@ func TestListReposTLS(t *testing.T) {
defer ts.Close()
var certs []byte
- if test.passCerts {
+ if test.passCerts == true {
for _, cert := range ts.TLS.Certificates {
for _, c := range cert.Certificate {
parsedCert, err := x509.ParseCertificate(c)
@@ -464,9 +469,9 @@ func TestListReposTLS(t *testing.T) {
}
}
- provider, err := NewBitbucketServerProviderBasicAuth(t.Context(), "user", "password", ts.URL, "PROJECT", true, "", test.tlsInsecure, certs)
+ provider, err := NewBitbucketServerProviderBasicAuth(context.Background(), "user", "password", ts.URL, "PROJECT", true, "", test.tlsInsecure, certs)
require.NoError(t, err)
- _, err = provider.ListRepos(t.Context(), "ssh")
+ _, err = provider.ListRepos(context.Background(), "ssh")
if test.requireErr {
require.Error(t, err)
} else {
@@ -483,9 +488,9 @@ func TestListReposBasicAuth(t *testing.T) {
defaultHandler(t)(w, r)
}))
defer ts.Close()
- provider, err := NewBitbucketServerProviderBasicAuth(t.Context(), "user", "password", ts.URL, "PROJECT", true, "", false, nil)
+ provider, err := NewBitbucketServerProviderBasicAuth(context.Background(), "user", "password", ts.URL, "PROJECT", true, "", false, nil)
require.NoError(t, err)
- repos, err := provider.ListRepos(t.Context(), "ssh")
+ repos, err := provider.ListRepos(context.Background(), "ssh")
verifyDefaultRepo(t, err, repos)
}
@@ -496,16 +501,17 @@ func TestListReposBearerAuth(t *testing.T) {
defaultHandler(t)(w, r)
}))
defer ts.Close()
- provider, err := NewBitbucketServerProviderBearerToken(t.Context(), "tolkien", ts.URL, "PROJECT", true, "", false, nil)
+ provider, err := NewBitbucketServerProviderBearerToken(context.Background(), "tolkien", ts.URL, "PROJECT", true, "", false, nil)
require.NoError(t, err)
- repos, err := provider.ListRepos(t.Context(), "ssh")
+ repos, err := provider.ListRepos(context.Background(), "ssh")
verifyDefaultRepo(t, err, repos)
}
func TestListReposDefaultBranch(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w 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" {
+ switch r.RequestURI {
+ case "/rest/api/1.0/projects/PROJECT/repos/REPO/branches/default":
_, err := io.WriteString(w, `{
"id": "refs/heads/default",
"displayId": "default",
@@ -522,9 +528,9 @@ func TestListReposDefaultBranch(t *testing.T) {
defaultHandler(t)(w, r)
}))
defer ts.Close()
- provider, err := NewBitbucketServerProviderNoAuth(t.Context(), ts.URL, "PROJECT", false, "", false, nil)
+ provider, err := NewBitbucketServerProviderNoAuth(context.Background(), ts.URL, "PROJECT", false, "", false, nil)
require.NoError(t, err)
- repos, err := provider.ListRepos(t.Context(), "ssh")
+ repos, err := provider.ListRepos(context.Background(), "ssh")
require.NoError(t, err)
assert.Len(t, repos, 1)
assert.Equal(t, Repository{
@@ -541,15 +547,16 @@ 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"))
- if r.RequestURI == "/rest/api/1.0/projects/PROJECT/repos/REPO/branches/default" {
+ switch r.RequestURI {
+ case "/rest/api/1.0/projects/PROJECT/repos/REPO/branches/default":
http.Error(w, "Not found", http.StatusNotFound)
}
defaultHandler(t)(w, r)
}))
defer ts.Close()
- provider, err := NewBitbucketServerProviderNoAuth(t.Context(), ts.URL, "PROJECT", false, "", false, nil)
+ provider, err := NewBitbucketServerProviderNoAuth(context.Background(), ts.URL, "PROJECT", false, "", false, nil)
require.NoError(t, err)
- repos, err := provider.ListRepos(t.Context(), "ssh")
+ repos, err := provider.ListRepos(context.Background(), "ssh")
require.NoError(t, err)
assert.Empty(t, repos)
}
@@ -557,15 +564,16 @@ 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"))
- if r.RequestURI == "/rest/api/1.0/projects/PROJECT/repos/REPO/branches/default" {
+ switch r.RequestURI {
+ case "/rest/api/1.0/projects/PROJECT/repos/REPO/branches/default":
http.Error(w, "Internal server error", http.StatusInternalServerError)
}
defaultHandler(t)(w, r)
}))
defer ts.Close()
- provider, err := NewBitbucketServerProviderNoAuth(t.Context(), ts.URL, "PROJECT", false, "", false, nil)
+ provider, err := NewBitbucketServerProviderNoAuth(context.Background(), ts.URL, "PROJECT", false, "", false, nil)
require.NoError(t, err)
- _, err = provider.ListRepos(t.Context(), "ssh")
+ _, err = provider.ListRepos(context.Background(), "ssh")
require.Error(t, err)
}
@@ -575,9 +583,9 @@ func TestListReposCloneProtocol(t *testing.T) {
defaultHandler(t)(w, r)
}))
defer ts.Close()
- provider, err := NewBitbucketServerProviderNoAuth(t.Context(), ts.URL, "PROJECT", true, "", false, nil)
+ provider, err := NewBitbucketServerProviderNoAuth(context.Background(), ts.URL, "PROJECT", true, "", false, nil)
require.NoError(t, err)
- repos, err := provider.ListRepos(t.Context(), "https")
+ repos, err := provider.ListRepos(context.Background(), "https")
require.NoError(t, err)
assert.Len(t, repos, 1)
assert.Equal(t, Repository{
@@ -597,9 +605,9 @@ func TestListReposUnknownProtocol(t *testing.T) {
defaultHandler(t)(w, r)
}))
defer ts.Close()
- provider, err := NewBitbucketServerProviderNoAuth(t.Context(), ts.URL, "PROJECT", true, "", false, nil)
+ provider, err := NewBitbucketServerProviderNoAuth(context.Background(), ts.URL, "PROJECT", true, "", false, nil)
require.NoError(t, err)
- _, errProtocol := provider.ListRepos(t.Context(), "http")
+ _, errProtocol := provider.ListRepos(context.Background(), "http")
require.Error(t, errProtocol)
}
@@ -635,37 +643,37 @@ func TestBitbucketServerHasPath(t *testing.T) {
}
}))
defer ts.Close()
- provider, err := NewBitbucketServerProviderNoAuth(t.Context(), ts.URL, "PROJECT", true, "", false, nil)
+ provider, err := NewBitbucketServerProviderNoAuth(context.Background(), ts.URL, "PROJECT", true, "", false, nil)
require.NoError(t, err)
repo := &Repository{
Organization: "PROJECT",
Repository: "REPO",
Branch: "main",
}
- ok, err := provider.RepoHasPath(t.Context(), repo, "pkg")
+ ok, err := provider.RepoHasPath(context.Background(), repo, "pkg")
require.NoError(t, err)
assert.True(t, ok)
- ok, err = provider.RepoHasPath(t.Context(), repo, "pkg/")
+ ok, err = provider.RepoHasPath(context.Background(), repo, "pkg/")
require.NoError(t, err)
assert.True(t, ok)
- ok, err = provider.RepoHasPath(t.Context(), repo, "anotherpkg/file.txt")
+ ok, err = provider.RepoHasPath(context.Background(), repo, "anotherpkg/file.txt")
require.NoError(t, err)
assert.True(t, ok)
- ok, err = provider.RepoHasPath(t.Context(), repo, "anotherpkg/missing.txt")
+ ok, err = provider.RepoHasPath(context.Background(), repo, "anotherpkg/missing.txt")
require.NoError(t, err)
assert.False(t, ok)
- ok, err = provider.RepoHasPath(t.Context(), repo, "notathing")
+ ok, err = provider.RepoHasPath(context.Background(), repo, "notathing")
require.NoError(t, err)
assert.False(t, ok)
- ok, err = provider.RepoHasPath(t.Context(), repo, "return-redirect")
+ ok, err = provider.RepoHasPath(context.Background(), repo, "return-redirect")
require.NoError(t, err)
assert.True(t, ok)
- _, err = provider.RepoHasPath(t.Context(), repo, "unauthorized-response")
+ _, err = provider.RepoHasPath(context.Background(), repo, "unauthorized-response")
require.Error(t, err)
}
diff --git a/applicationset/services/scm_provider/gitea.go b/applicationset/services/scm_provider/gitea.go
index b633d0c5ef..500aa0e981 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(owner, token, url string, allBranches, insecure bool) (*GiteaProvider, error) {
+func NewGiteaProvider(ctx context.Context, owner, token, url string, allBranches, insecure bool) (*GiteaProvider, error) {
if token == "" {
token = os.Getenv("GITEA_TOKEN")
}
@@ -46,7 +46,7 @@ func NewGiteaProvider(owner, token, url string, allBranches, insecure bool) (*Gi
}, nil
}
-func (g *GiteaProvider) GetBranches(_ context.Context, repo *Repository) ([]*Repository, error) {
+func (g *GiteaProvider) GetBranches(ctx 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(_ context.Context, repo *Repository) ([]*Rep
return repos, nil
}
-func (g *GiteaProvider) ListRepos(_ context.Context, cloneProtocol string) ([]*Repository, error) {
+func (g *GiteaProvider) ListRepos(ctx context.Context, cloneProtocol string) ([]*Repository, error) {
repos := []*Repository{}
repoOpts := gitea.ListOrgReposOptions{}
giteaRepos, _, err := g.client.ListOrgRepos(g.owner, repoOpts)
@@ -126,15 +126,15 @@ func (g *GiteaProvider) ListRepos(_ context.Context, cloneProtocol string) ([]*R
return repos, nil
}
-func (g *GiteaProvider) RepoHasPath(_ context.Context, repo *Repository, path string) (bool, error) {
+func (g *GiteaProvider) RepoHasPath(ctx 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
}
+ if fmt.Sprint(err) == "expect file, got directory" {
+ return true, nil
+ }
if err != nil {
- if err.Error() == "expect file, got directory" {
- return true, nil
- }
return false, err
}
return true, nil
diff --git a/applicationset/services/scm_provider/gitea_test.go b/applicationset/services/scm_provider/gitea_test.go
index e14c56669f..1253d30c9a 100644
--- a/applicationset/services/scm_provider/gitea_test.go
+++ b/applicationset/services/scm_provider/gitea_test.go
@@ -1,6 +1,7 @@
package scm_provider
import (
+ "context"
"io"
"net/http"
"net/http/httptest"
@@ -9,8 +10,8 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
- "github.com/argoproj/argo-cd/v3/applicationset/services/scm_provider/testdata"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/applicationset/services/scm_provider/testdata"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
)
func giteaMockHandler(t *testing.T) func(http.ResponseWriter, *http.Request) {
@@ -303,8 +304,8 @@ func TestGiteaListRepos(t *testing.T) {
defer ts.Close()
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
- provider, _ := NewGiteaProvider("test-argocd", "", ts.URL, c.allBranches, false)
- rawRepos, err := ListRepos(t.Context(), provider, c.filters, c.proto)
+ provider, _ := NewGiteaProvider(context.Background(), "test-argocd", "", ts.URL, c.allBranches, false)
+ rawRepos, err := ListRepos(context.Background(), provider, c.filters, c.proto)
if c.hasError {
require.Error(t, err)
} else {
@@ -333,7 +334,7 @@ func TestGiteaHasPath(t *testing.T) {
giteaMockHandler(t)(w, r)
}))
defer ts.Close()
- host, _ := NewGiteaProvider("gitea", "", ts.URL, false, false)
+ host, _ := NewGiteaProvider(context.Background(), "gitea", "", ts.URL, false, false)
repo := &Repository{
Organization: "gitea",
Repository: "go-sdk",
@@ -341,19 +342,19 @@ func TestGiteaHasPath(t *testing.T) {
}
t.Run("file exists", func(t *testing.T) {
- ok, err := host.RepoHasPath(t.Context(), repo, "README.md")
+ ok, err := host.RepoHasPath(context.Background(), repo, "README.md")
require.NoError(t, err)
assert.True(t, ok)
})
t.Run("directory exists", func(t *testing.T) {
- ok, err := host.RepoHasPath(t.Context(), repo, "gitea")
+ ok, err := host.RepoHasPath(context.Background(), repo, "gitea")
require.NoError(t, err)
assert.True(t, ok)
})
t.Run("does not exists", func(t *testing.T) {
- ok, err := host.RepoHasPath(t.Context(), repo, "notathing")
+ ok, err := host.RepoHasPath(context.Background(), repo, "notathing")
require.NoError(t, err)
assert.False(t, ok)
})
diff --git a/applicationset/services/scm_provider/github.go b/applicationset/services/scm_provider/github.go
index 41680b0145..2e2f2a7faf 100644
--- a/applicationset/services/scm_provider/github.go
+++ b/applicationset/services/scm_provider/github.go
@@ -6,7 +6,8 @@ import (
"net/http"
"os"
- "github.com/google/go-github/v69/github"
+ "github.com/google/go-github/v66/github"
+ "golang.org/x/oauth2"
)
type GithubProvider struct {
@@ -17,19 +18,21 @@ type GithubProvider struct {
var _ SCMProviderService = &GithubProvider{}
-func NewGithubProvider(organization string, token string, url string, allBranches bool) (*GithubProvider, error) {
+func NewGithubProvider(ctx context.Context, organization string, token string, url string, allBranches bool) (*GithubProvider, error) {
+ var ts oauth2.TokenSource
// Undocumented environment variable to set a default token, to be used in testing to dodge anonymous rate limits.
if token == "" {
token = os.Getenv("GITHUB_TOKEN")
}
- httpClient := &http.Client{}
+ if token != "" {
+ ts = oauth2.StaticTokenSource(
+ &oauth2.Token{AccessToken: token},
+ )
+ }
+ httpClient := oauth2.NewClient(ctx, ts)
var client *github.Client
if url == "" {
- if token == "" {
- client = github.NewClient(httpClient)
- } else {
- client = github.NewClient(httpClient).WithAuthToken(token)
- }
+ client = github.NewClient(httpClient)
} else {
var err error
client, err = github.NewClient(httpClient).WithEnterpriseURLs(url, url)
diff --git a/applicationset/services/scm_provider/github_app.go b/applicationset/services/scm_provider/github_app.go
index 8ee26cec41..5429ed48ee 100644
--- a/applicationset/services/scm_provider/github_app.go
+++ b/applicationset/services/scm_provider/github_app.go
@@ -1,8 +1,8 @@
package scm_provider
import (
- "github.com/argoproj/argo-cd/v3/applicationset/services/github_app_auth"
- "github.com/argoproj/argo-cd/v3/applicationset/services/internal/github_app"
+ "github.com/argoproj/argo-cd/v2/applicationset/services/github_app_auth"
+ "github.com/argoproj/argo-cd/v2/applicationset/services/internal/github_app"
)
func NewGithubAppProviderFor(g github_app_auth.Authentication, organization string, url string, allBranches bool) (*GithubProvider, error) {
diff --git a/applicationset/services/scm_provider/github_test.go b/applicationset/services/scm_provider/github_test.go
index 42e4635e98..747f895ab7 100644
--- a/applicationset/services/scm_provider/github_test.go
+++ b/applicationset/services/scm_provider/github_test.go
@@ -1,6 +1,7 @@
package scm_provider
import (
+ "context"
"io"
"net/http"
"net/http/httptest"
@@ -9,7 +10,7 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
)
func githubMockHandler(t *testing.T) func(http.ResponseWriter, *http.Request) {
@@ -242,8 +243,8 @@ func TestGithubListRepos(t *testing.T) {
defer ts.Close()
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
- provider, _ := NewGithubProvider("argoproj", "", ts.URL, c.allBranches)
- rawRepos, err := ListRepos(t.Context(), provider, c.filters, c.proto)
+ provider, _ := NewGithubProvider(context.Background(), "argoproj", "", ts.URL, c.allBranches)
+ rawRepos, err := ListRepos(context.Background(), provider, c.filters, c.proto)
if c.hasError {
require.Error(t, err)
} else {
@@ -272,17 +273,17 @@ func TestGithubHasPath(t *testing.T) {
githubMockHandler(t)(w, r)
}))
defer ts.Close()
- host, _ := NewGithubProvider("argoproj", "", ts.URL, false)
+ host, _ := NewGithubProvider(context.Background(), "argoproj", "", ts.URL, false)
repo := &Repository{
Organization: "argoproj",
Repository: "argo-cd",
Branch: "master",
}
- ok, err := host.RepoHasPath(t.Context(), repo, "pkg/")
+ ok, err := host.RepoHasPath(context.Background(), repo, "pkg/")
require.NoError(t, err)
assert.True(t, ok)
- ok, err = host.RepoHasPath(t.Context(), repo, "notathing/")
+ ok, err = host.RepoHasPath(context.Background(), repo, "notathing/")
require.NoError(t, err)
assert.False(t, ok)
}
@@ -292,13 +293,13 @@ func TestGithubGetBranches(t *testing.T) {
githubMockHandler(t)(w, r)
}))
defer ts.Close()
- host, _ := NewGithubProvider("argoproj", "", ts.URL, false)
+ host, _ := NewGithubProvider(context.Background(), "argoproj", "", ts.URL, false)
repo := &Repository{
Organization: "argoproj",
Repository: "argo-cd",
Branch: "master",
}
- repos, err := host.GetBranches(t.Context(), repo)
+ repos, err := host.GetBranches(context.Background(), repo)
if err != nil {
require.NoError(t, err)
} else {
@@ -310,12 +311,12 @@ func TestGithubGetBranches(t *testing.T) {
Repository: "applicationset",
Branch: "main",
}
- _, err = host.GetBranches(t.Context(), repo2)
+ _, err = host.GetBranches(context.Background(), repo2)
require.NoError(t, err)
// Get all branches
host.allBranches = true
- repos, err = host.GetBranches(t.Context(), repo)
+ repos, err = host.GetBranches(context.Background(), repo)
if err != nil {
require.NoError(t, err)
} else {
diff --git a/applicationset/services/scm_provider/gitlab.go b/applicationset/services/scm_provider/gitlab.go
index 2ab3234c5f..e77455296b 100644
--- a/applicationset/services/scm_provider/gitlab.go
+++ b/applicationset/services/scm_provider/gitlab.go
@@ -8,9 +8,9 @@ import (
"os"
"github.com/hashicorp/go-retryablehttp"
- gitlab "gitlab.com/gitlab-org/api/client-go"
+ "github.com/xanzy/go-gitlab"
- "github.com/argoproj/argo-cd/v3/applicationset/utils"
+ "github.com/argoproj/argo-cd/v2/applicationset/utils"
)
type GitlabProvider struct {
@@ -24,7 +24,7 @@ type GitlabProvider struct {
var _ SCMProviderService = &GitlabProvider{}
-func NewGitlabProvider(organization string, token string, url string, allBranches, includeSubgroups, includeSharedProjects, insecure bool, scmRootCAPath, topic string, caCerts []byte) (*GitlabProvider, error) {
+func NewGitlabProvider(ctx context.Context, 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(_ context.Context, cloneProtocol string) ([]*Repository, error) {
+func (g *GitlabProvider) ListRepos(ctx 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 9f37de4bc6..bf980538d5 100644
--- a/applicationset/services/scm_provider/gitlab_test.go
+++ b/applicationset/services/scm_provider/gitlab_test.go
@@ -1,6 +1,7 @@
package scm_provider
import (
+ "context"
"crypto/x509"
"encoding/pem"
"fmt"
@@ -12,7 +13,7 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
)
func gitlabMockHandler(t *testing.T) func(http.ResponseWriter, *http.Request) {
@@ -1150,8 +1151,8 @@ func TestGitlabListRepos(t *testing.T) {
}))
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
- provider, _ := NewGitlabProvider("test-argocd-proton", "", ts.URL, c.allBranches, c.includeSubgroups, c.includeSharedProjects, c.insecure, "", c.topic, nil)
- rawRepos, err := ListRepos(t.Context(), provider, c.filters, c.proto)
+ provider, _ := NewGitlabProvider(context.Background(), "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)
} else {
@@ -1189,7 +1190,7 @@ func TestGitlabHasPath(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gitlabMockHandler(t)(w, r)
}))
- host, _ := NewGitlabProvider("test-argocd-proton", "", ts.URL, false, true, true, false, "", "", nil)
+ host, _ := NewGitlabProvider(context.Background(), "test-argocd-proton", "", ts.URL, false, true, true, false, "", "", nil)
repo := &Repository{
Organization: "test-argocd-proton",
Repository: "argocd",
@@ -1234,7 +1235,7 @@ func TestGitlabHasPath(t *testing.T) {
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
- ok, err := host.RepoHasPath(t.Context(), repo, c.path)
+ ok, err := host.RepoHasPath(context.Background(), repo, c.path)
require.NoError(t, err)
assert.Equal(t, c.exists, ok)
})
@@ -1245,14 +1246,14 @@ func TestGitlabGetBranches(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gitlabMockHandler(t)(w, r)
}))
- host, _ := NewGitlabProvider("test-argocd-proton", "", ts.URL, false, true, true, false, "", "", nil)
+ host, _ := NewGitlabProvider(context.Background(), "test-argocd-proton", "", ts.URL, false, true, true, false, "", "", nil)
repo := &Repository{
RepositoryId: 27084533,
Branch: "master",
}
t.Run("branch exists", func(t *testing.T) {
- repos, err := host.GetBranches(t.Context(), repo)
+ repos, err := host.GetBranches(context.Background(), repo)
require.NoError(t, err)
assert.Equal(t, "master", repos[0].Branch)
})
@@ -1262,7 +1263,7 @@ func TestGitlabGetBranches(t *testing.T) {
Branch: "foo",
}
t.Run("unknown branch", func(t *testing.T) {
- _, err := host.GetBranches(t.Context(), repo2)
+ _, err := host.GetBranches(context.Background(), repo2)
require.NoError(t, err)
})
}
@@ -1309,7 +1310,7 @@ func TestGetBranchesTLS(t *testing.T) {
defer ts.Close()
var certs []byte
- if test.passCerts {
+ if test.passCerts == true {
for _, cert := range ts.TLS.Certificates {
for _, c := range cert.Certificate {
parsedCert, err := x509.ParseCertificate(c)
@@ -1322,13 +1323,13 @@ func TestGetBranchesTLS(t *testing.T) {
}
}
- host, err := NewGitlabProvider("test-argocd-proton", "", ts.URL, false, true, true, test.tlsInsecure, "", "", certs)
+ host, err := NewGitlabProvider(context.Background(), "test-argocd-proton", "", ts.URL, false, true, true, test.tlsInsecure, "", "", certs)
require.NoError(t, err)
repo := &Repository{
RepositoryId: 27084533,
Branch: "master",
}
- _, err = host.GetBranches(t.Context(), repo)
+ _, err = host.GetBranches(context.Background(), repo)
if test.requireErr {
require.Error(t, err)
} else {
diff --git a/applicationset/services/scm_provider/types.go b/applicationset/services/scm_provider/types.go
index b839088392..dde6db03c7 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 any
+ RepositoryId interface{}
}
type SCMProviderService interface {
diff --git a/applicationset/services/scm_provider/utils.go b/applicationset/services/scm_provider/utils.go
index d9d8ac63a6..b7cdbf4606 100644
--- a/applicationset/services/scm_provider/utils.go
+++ b/applicationset/services/scm_provider/utils.go
@@ -6,7 +6,7 @@ import (
"regexp"
"strings"
- argoprojiov1alpha1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ argoprojiov1alpha1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
)
func compileFilters(filters []argoprojiov1alpha1.SCMProviderGeneratorFilter) ([]*Filter, error) {
@@ -172,10 +172,9 @@ func getApplicableFilters(filters []*Filter) map[FilterType][]*Filter {
FilterTypeRepo: {},
}
for _, filter := range filters {
- switch filter.FilterType {
- case FilterTypeBranch:
+ if filter.FilterType == FilterTypeBranch {
filterMap[FilterTypeBranch] = append(filterMap[FilterTypeBranch], filter)
- case FilterTypeRepo:
+ } else if filter.FilterType == FilterTypeRepo {
filterMap[FilterTypeRepo] = append(filterMap[FilterTypeRepo], filter)
}
}
diff --git a/applicationset/services/scm_provider/utils_test.go b/applicationset/services/scm_provider/utils_test.go
index 5a805484ff..83c6c4fc23 100644
--- a/applicationset/services/scm_provider/utils_test.go
+++ b/applicationset/services/scm_provider/utils_test.go
@@ -1,13 +1,14 @@
package scm_provider
import (
+ "context"
"regexp"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
- argoprojiov1alpha1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ argoprojiov1alpha1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
)
func strp(s string) *string {
@@ -36,7 +37,7 @@ func TestFilterRepoMatch(t *testing.T) {
RepositoryMatch: strp("n|hr"),
},
}
- repos, err := ListRepos(t.Context(), provider, filters, "")
+ repos, err := ListRepos(context.Background(), provider, filters, "")
require.NoError(t, err)
assert.Len(t, repos, 2)
assert.Equal(t, "one", repos[0].Repository)
@@ -65,7 +66,7 @@ func TestFilterLabelMatch(t *testing.T) {
LabelMatch: strp("^prod-.*$"),
},
}
- repos, err := ListRepos(t.Context(), provider, filters, "")
+ repos, err := ListRepos(context.Background(), provider, filters, "")
require.NoError(t, err)
assert.Len(t, repos, 2)
assert.Equal(t, "one", repos[0].Repository)
@@ -91,7 +92,7 @@ func TestFilterPathExists(t *testing.T) {
PathsExist: []string{"two"},
},
}
- repos, err := ListRepos(t.Context(), provider, filters, "")
+ repos, err := ListRepos(context.Background(), provider, filters, "")
require.NoError(t, err)
assert.Len(t, repos, 1)
assert.Equal(t, "two", repos[0].Repository)
@@ -116,7 +117,7 @@ func TestFilterPathDoesntExists(t *testing.T) {
PathsDoNotExist: []string{"two"},
},
}
- repos, err := ListRepos(t.Context(), provider, filters, "")
+ repos, err := ListRepos(context.Background(), provider, filters, "")
require.NoError(t, err)
assert.Len(t, repos, 2)
}
@@ -134,7 +135,7 @@ func TestFilterRepoMatchBadRegexp(t *testing.T) {
RepositoryMatch: strp("("),
},
}
- _, err := ListRepos(t.Context(), provider, filters, "")
+ _, err := ListRepos(context.Background(), provider, filters, "")
require.Error(t, err)
}
@@ -151,7 +152,7 @@ func TestFilterLabelMatchBadRegexp(t *testing.T) {
LabelMatch: strp("("),
},
}
- _, err := ListRepos(t.Context(), provider, filters, "")
+ _, err := ListRepos(context.Background(), provider, filters, "")
require.Error(t, err)
}
@@ -185,7 +186,7 @@ func TestFilterBranchMatch(t *testing.T) {
BranchMatch: strp("w"),
},
}
- repos, err := ListRepos(t.Context(), provider, filters, "")
+ repos, err := ListRepos(context.Background(), provider, filters, "")
require.NoError(t, err)
assert.Len(t, repos, 2)
assert.Equal(t, "one", repos[0].Repository)
@@ -217,7 +218,7 @@ func TestMultiFilterAnd(t *testing.T) {
LabelMatch: strp("^prod-.*$"),
},
}
- repos, err := ListRepos(t.Context(), provider, filters, "")
+ repos, err := ListRepos(context.Background(), provider, filters, "")
require.NoError(t, err)
assert.Len(t, repos, 1)
assert.Equal(t, "two", repos[0].Repository)
@@ -248,7 +249,7 @@ func TestMultiFilterOr(t *testing.T) {
LabelMatch: strp("^prod-.*$"),
},
}
- repos, err := ListRepos(t.Context(), provider, filters, "")
+ repos, err := ListRepos(context.Background(), provider, filters, "")
require.NoError(t, err)
assert.Len(t, repos, 3)
assert.Equal(t, "one", repos[0].Repository)
@@ -274,7 +275,7 @@ func TestNoFilters(t *testing.T) {
},
}
filters := []argoprojiov1alpha1.SCMProviderGeneratorFilter{}
- repos, err := ListRepos(t.Context(), provider, filters, "")
+ repos, err := ListRepos(context.Background(), provider, filters, "")
require.NoError(t, err)
assert.Len(t, repos, 3)
assert.Equal(t, "one", repos[0].Repository)
diff --git a/applicationset/status/resource_status.go b/applicationset/status/resource_status.go
index f1ac822550..4e9db5ff56 100644
--- a/applicationset/status/resource_status.go
+++ b/applicationset/status/resource_status.go
@@ -1,23 +1,37 @@
package status
import (
- argov1alpha1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ argov1alpha1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
)
func BuildResourceStatus(statusMap map[string]argov1alpha1.ResourceStatus, apps []argov1alpha1.Application) map[string]argov1alpha1.ResourceStatus {
appMap := map[string]argov1alpha1.Application{}
for _, app := range apps {
+ appCopy := app
appMap[app.Name] = app
gvk := app.GroupVersionKind()
- var status argov1alpha1.ResourceStatus
+ // Create status if it does not exist
+ status, ok := statusMap[app.Name]
+ if !ok {
+ status = argov1alpha1.ResourceStatus{
+ Group: gvk.Group,
+ Version: gvk.Version,
+ Kind: gvk.Kind,
+ Name: app.Name,
+ Namespace: app.Namespace,
+ Status: app.Status.Sync.Status,
+ Health: &appCopy.Status.Health,
+ }
+ }
+
status.Group = gvk.Group
status.Version = gvk.Version
status.Kind = gvk.Kind
status.Name = app.Name
status.Namespace = app.Namespace
status.Status = app.Status.Sync.Status
- status.Health = &argov1alpha1.HealthStatus{Status: app.Status.Health.Status}
+ status.Health = &appCopy.Status.Health
statusMap[app.Name] = status
}
diff --git a/applicationset/utils/applicationset_lister.go b/applicationset/utils/applicationset_lister.go
index e7764f6fc0..5e9d659363 100644
--- a/applicationset/utils/applicationset_lister.go
+++ b/applicationset/utils/applicationset_lister.go
@@ -6,8 +6,8 @@ import (
"k8s.io/apimachinery/pkg/labels"
ctrlclient "sigs.k8s.io/controller-runtime/pkg/client"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- listers "github.com/argoproj/argo-cd/v3/pkg/client/listers/application/v1alpha1"
+ . "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+ . "github.com/argoproj/argo-cd/v2/pkg/client/listers/application/v1alpha1"
)
// Implements AppsetLister interface with controller-runtime client
@@ -15,16 +15,16 @@ type AppsetLister struct {
Client ctrlclient.Client
}
-func NewAppsetLister(client ctrlclient.Client) listers.ApplicationSetLister {
+func NewAppsetLister(client ctrlclient.Client) ApplicationSetLister {
return &AppsetLister{Client: client}
}
-func (l *AppsetLister) List(_ labels.Selector) (ret []*v1alpha1.ApplicationSet, err error) {
+func (l *AppsetLister) List(selector labels.Selector) (ret []*ApplicationSet, err error) {
return clientListAppsets(l.Client, ctrlclient.ListOptions{})
}
// ApplicationSets returns an object that can list and get ApplicationSets.
-func (l *AppsetLister) ApplicationSets(namespace string) listers.ApplicationSetNamespaceLister {
+func (l *AppsetLister) ApplicationSets(namespace string) ApplicationSetNamespaceLister {
return &appsetNamespaceLister{
Client: l.Client,
Namespace: namespace,
@@ -37,19 +37,19 @@ type appsetNamespaceLister struct {
Namespace string
}
-func (n *appsetNamespaceLister) List(_ labels.Selector) (ret []*v1alpha1.ApplicationSet, err error) {
+func (n *appsetNamespaceLister) List(selector labels.Selector) (ret []*ApplicationSet, err error) {
return clientListAppsets(n.Client, ctrlclient.ListOptions{Namespace: n.Namespace})
}
-func (n *appsetNamespaceLister) Get(_ string) (*v1alpha1.ApplicationSet, error) {
- appset := v1alpha1.ApplicationSet{}
+func (n *appsetNamespaceLister) Get(name string) (*ApplicationSet, error) {
+ appset := ApplicationSet{}
err := n.Client.Get(context.TODO(), ctrlclient.ObjectKeyFromObject(&appset), &appset)
return &appset, err
}
-func clientListAppsets(client ctrlclient.Client, listOptions ctrlclient.ListOptions) (ret []*v1alpha1.ApplicationSet, err error) {
- var appsetlist v1alpha1.ApplicationSetList
- var results []*v1alpha1.ApplicationSet
+func clientListAppsets(client ctrlclient.Client, listOptions ctrlclient.ListOptions) (ret []*ApplicationSet, err error) {
+ var appsetlist ApplicationSetList
+ var results []*ApplicationSet
err = client.List(context.TODO(), &appsetlist, &listOptions)
diff --git a/applicationset/utils/clusterUtils.go b/applicationset/utils/clusterUtils.go
index 5ba1f4584d..b95854e600 100644
--- a/applicationset/utils/clusterUtils.go
+++ b/applicationset/utils/clusterUtils.go
@@ -3,23 +3,104 @@ package utils
import (
"context"
"fmt"
+ "sync"
- "github.com/argoproj/argo-cd/v3/common"
- appv1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- "github.com/argoproj/argo-cd/v3/util/db"
+ "github.com/argoproj/argo-cd/v2/common"
+ appv1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/util/db"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
)
-// ClusterSpecifier contains only the name and server URL of a cluster. We use this struct to avoid partially-populating
-// the full Cluster struct, which would be misleading.
-type ClusterSpecifier struct {
- Name string
- Server string
+// The contents of this file are from
+// github.com/argoproj/argo-cd/util/db/cluster.go
+//
+// The main difference is that ListClusters(...) calls the kubeclient directly,
+// via `g.clientset.CoreV1().Secrets`, rather than using the `db.listClusterSecrets()``
+// which appears to have a race condition on when it is called.
+//
+// I was reminded of this issue that I opened, which might be related:
+// https://github.com/argoproj/argo-cd/issues/4755
+//
+// I hope to upstream this change in some form, so that we do not need to worry about
+// Argo CD changing the logic on us.
+
+var (
+ localCluster = appv1.Cluster{
+ Name: "in-cluster",
+ Server: appv1.KubernetesInternalAPIServerAddr,
+ ConnectionState: appv1.ConnectionState{Status: appv1.ConnectionStatusSuccessful},
+ }
+ initLocalCluster sync.Once
+)
+
+const (
+ ArgoCDSecretTypeLabel = "argocd.argoproj.io/secret-type"
+ ArgoCDSecretTypeCluster = "cluster"
+)
+
+// ValidateDestination checks:
+// if we used destination name we infer the server url
+// if we used both name and server then we return an invalid spec error
+func ValidateDestination(ctx context.Context, dest *appv1.ApplicationDestination, clientset kubernetes.Interface, argoCDNamespace string) error {
+ if dest.IsServerInferred() && dest.IsNameInferred() {
+ return fmt.Errorf("application destination can't have both name and server inferred: %s %s", dest.Name, dest.Server)
+ }
+ if dest.Name != "" {
+ if dest.Server == "" {
+ server, err := getDestinationBy(ctx, dest.Name, clientset, argoCDNamespace, true)
+ if err != nil {
+ return fmt.Errorf("unable to find destination server: %w", err)
+ }
+ if server == "" {
+ return fmt.Errorf("application references destination cluster %s which does not exist", dest.Name)
+ }
+ dest.SetInferredServer(server)
+ } else if !dest.IsServerInferred() && !dest.IsNameInferred() {
+ return fmt.Errorf("application destination can't have both name and server defined: %s %s", dest.Name, dest.Server)
+ }
+ } else if dest.Server != "" {
+ if dest.Name == "" {
+ serverName, err := getDestinationBy(ctx, dest.Server, clientset, argoCDNamespace, false)
+ if err != nil {
+ return fmt.Errorf("unable to find destination server: %w", err)
+ }
+ if serverName == "" {
+ return fmt.Errorf("application references destination cluster %s which does not exist", dest.Server)
+ }
+ dest.SetInferredName(serverName)
+ }
+ }
+ return nil
}
-func ListClusters(ctx context.Context, clientset kubernetes.Interface, namespace string) ([]ClusterSpecifier, error) {
+func getDestinationBy(ctx context.Context, cluster string, clientset kubernetes.Interface, argoCDNamespace string, byName bool) (string, error) {
+ // settingsMgr := settings.NewSettingsManager(context.TODO(), clientset, namespace)
+ // argoDB := db.NewDB(namespace, settingsMgr, clientset)
+ // clusterList, err := argoDB.ListClusters(ctx)
+ clusterList, err := ListClusters(ctx, clientset, argoCDNamespace)
+ if err != nil {
+ return "", err
+ }
+ var servers []string
+ for _, c := range clusterList.Items {
+ if byName && c.Name == cluster {
+ servers = append(servers, c.Server)
+ }
+ if !byName && c.Server == cluster {
+ servers = append(servers, c.Name)
+ }
+ }
+ if len(servers) > 1 {
+ return "", fmt.Errorf("there are %d clusters with the same name: %v", len(servers), servers)
+ } else if len(servers) == 0 {
+ return "", fmt.Errorf("there are no clusters with this name: %s", cluster)
+ }
+ return servers[0], nil
+}
+
+func ListClusters(ctx context.Context, clientset kubernetes.Interface, namespace string) (*appv1.ClusterList, error) {
clusterSecretsList, err := clientset.CoreV1().Secrets(namespace).List(ctx,
metav1.ListOptions{LabelSelector: common.LabelKeySecretType + "=" + common.LabelValueSecretTypeCluster})
if err != nil {
@@ -32,29 +113,54 @@ func ListClusters(ctx context.Context, clientset kubernetes.Interface, namespace
clusterSecrets := clusterSecretsList.Items
- clusterList := make([]ClusterSpecifier, len(clusterSecrets))
-
+ clusterList := appv1.ClusterList{
+ Items: make([]appv1.Cluster, len(clusterSecrets)),
+ }
hasInClusterCredentials := false
for i, clusterSecret := range clusterSecrets {
+ // This line has changed from the original Argo CD code: now receives an error, and handles it
cluster, err := db.SecretToCluster(&clusterSecret)
if err != nil || cluster == nil {
return nil, fmt.Errorf("unable to convert cluster secret to cluster object '%s': %w", clusterSecret.Name, err)
}
- clusterList[i] = ClusterSpecifier{
- Name: cluster.Name,
- Server: cluster.Server,
- }
+
+ // db.SecretToCluster populates these, but they're not meant to be available to the caller.
+ cluster.Labels = nil
+ cluster.Annotations = nil
+
+ clusterList.Items[i] = *cluster
if cluster.Server == appv1.KubernetesInternalAPIServerAddr {
hasInClusterCredentials = true
}
}
if !hasInClusterCredentials {
- // There was no secret for the in-cluster config, so we add it here. We don't fully-populate the Cluster struct,
- // since only the name and server fields are used by the generator.
- clusterList = append(clusterList, ClusterSpecifier{
- Name: "in-cluster",
- Server: appv1.KubernetesInternalAPIServerAddr,
- })
+ localCluster := getLocalCluster(clientset)
+ if localCluster != nil {
+ clusterList.Items = append(clusterList.Items, *localCluster)
+ }
}
- return clusterList, nil
+ return &clusterList, nil
+}
+
+func getLocalCluster(clientset kubernetes.Interface) *appv1.Cluster {
+ initLocalCluster.Do(func() {
+ info, err := clientset.Discovery().ServerVersion()
+ if err == nil {
+ // nolint:staticcheck
+ localCluster.ServerVersion = fmt.Sprintf("%s.%s", info.Major, info.Minor)
+ // nolint:staticcheck
+ localCluster.ConnectionState = appv1.ConnectionState{Status: appv1.ConnectionStatusSuccessful}
+ } else {
+ // nolint:staticcheck
+ localCluster.ConnectionState = appv1.ConnectionState{
+ Status: appv1.ConnectionStatusFailed,
+ Message: err.Error(),
+ }
+ }
+ })
+ cluster := localCluster.DeepCopy()
+ now := metav1.Now()
+ // nolint:staticcheck
+ cluster.ConnectionState.ModifiedAt = &now
+ return cluster
}
diff --git a/applicationset/utils/clusterUtils_test.go b/applicationset/utils/clusterUtils_test.go
new file mode 100644
index 0000000000..7d71db9f97
--- /dev/null
+++ b/applicationset/utils/clusterUtils_test.go
@@ -0,0 +1,135 @@
+package utils
+
+import (
+ "context"
+ "fmt"
+ "testing"
+
+ "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/runtime"
+ "k8s.io/client-go/kubernetes/fake"
+ kubetesting "k8s.io/client-go/testing"
+
+ argoappv1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+)
+
+const (
+ fakeNamespace = "fake-ns"
+)
+
+func createClusterSecret(secretName string, clusterName string, clusterServer string) *corev1.Secret {
+ secret := &corev1.Secret{
+ ObjectMeta: metav1.ObjectMeta{
+ Name: secretName,
+ Namespace: fakeNamespace,
+ Labels: map[string]string{
+ ArgoCDSecretTypeLabel: ArgoCDSecretTypeCluster,
+ },
+ },
+ Data: map[string][]byte{
+ "name": []byte(clusterName),
+ "server": []byte(clusterServer),
+ "config": []byte("{\"username\":\"foo\",\"password\":\"foo\"}"),
+ },
+ }
+
+ return secret
+}
+
+// From util/argo/argo_test.go
+// (ported to use kubeclientset)
+func TestValidateDestination(t *testing.T) {
+ t.Run("Validate destination with server url", func(t *testing.T) {
+ dest := argoappv1.ApplicationDestination{
+ Server: "https://127.0.0.1:6443",
+ Namespace: "default",
+ }
+
+ secret := createClusterSecret("my-secret", "minikube", "https://127.0.0.1:6443")
+ objects := []runtime.Object{}
+ objects = append(objects, secret)
+ kubeclientset := fake.NewSimpleClientset(objects...)
+
+ appCond := ValidateDestination(context.Background(), &dest, kubeclientset, fakeNamespace)
+ require.NoError(t, appCond)
+ assert.False(t, dest.IsServerInferred())
+ })
+
+ t.Run("Validate destination with server name", func(t *testing.T) {
+ dest := argoappv1.ApplicationDestination{
+ Name: "minikube",
+ }
+
+ secret := createClusterSecret("my-secret", "minikube", "https://127.0.0.1:6443")
+ objects := []runtime.Object{}
+ objects = append(objects, secret)
+ kubeclientset := fake.NewSimpleClientset(objects...)
+
+ appCond := ValidateDestination(context.Background(), &dest, kubeclientset, fakeNamespace)
+ require.NoError(t, appCond)
+ assert.Equal(t, "https://127.0.0.1:6443", dest.Server)
+ assert.True(t, dest.IsServerInferred())
+ })
+
+ t.Run("Error when having both server url and name", func(t *testing.T) {
+ dest := argoappv1.ApplicationDestination{
+ Server: "https://127.0.0.1:6443",
+ Name: "minikube",
+ Namespace: "default",
+ }
+
+ err := ValidateDestination(context.Background(), &dest, nil, fakeNamespace)
+ assert.Equal(t, "application destination can't have both name and server defined: minikube https://127.0.0.1:6443", err.Error())
+ assert.False(t, dest.IsServerInferred())
+ })
+
+ t.Run("List clusters fails", func(t *testing.T) {
+ dest := argoappv1.ApplicationDestination{
+ Name: "minikube",
+ }
+ kubeclientset := fake.NewSimpleClientset()
+
+ kubeclientset.PrependReactor("list", "*", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) {
+ return true, nil, fmt.Errorf("an error occurred")
+ })
+
+ err := ValidateDestination(context.Background(), &dest, kubeclientset, fakeNamespace)
+ assert.Equal(t, "unable to find destination server: an error occurred", err.Error())
+ assert.False(t, dest.IsServerInferred())
+ })
+
+ t.Run("Destination cluster does not exist", func(t *testing.T) {
+ dest := argoappv1.ApplicationDestination{
+ Name: "minikube",
+ }
+
+ secret := createClusterSecret("dind", "dind", "https://127.0.0.1:6443")
+ objects := []runtime.Object{}
+ objects = append(objects, secret)
+ kubeclientset := fake.NewSimpleClientset(objects...)
+
+ err := ValidateDestination(context.Background(), &dest, kubeclientset, fakeNamespace)
+ assert.Equal(t, "unable to find destination server: there are no clusters with this name: minikube", err.Error())
+ assert.False(t, dest.IsServerInferred())
+ })
+
+ t.Run("Validate too many clusters with the same name", func(t *testing.T) {
+ dest := argoappv1.ApplicationDestination{
+ Name: "dind",
+ }
+
+ secret := createClusterSecret("dind", "dind", "https://127.0.0.1:2443")
+ secret2 := createClusterSecret("dind2", "dind", "https://127.0.0.1:8443")
+
+ objects := []runtime.Object{}
+ objects = append(objects, secret, secret2)
+ kubeclientset := fake.NewSimpleClientset(objects...)
+
+ err := ValidateDestination(context.Background(), &dest, kubeclientset, fakeNamespace)
+ assert.Equal(t, "unable to find destination server: there are 2 clusters with the same name: [https://127.0.0.1:2443 https://127.0.0.1:8443]", err.Error())
+ assert.False(t, dest.IsServerInferred())
+ })
+}
diff --git a/applicationset/utils/createOrUpdate.go b/applicationset/utils/createOrUpdate.go
index 1367e11cde..c602f002b0 100644
--- a/applicationset/utils/createOrUpdate.go
+++ b/applicationset/utils/createOrUpdate.go
@@ -3,7 +3,6 @@ package utils
import (
"context"
"encoding/json"
- stderrors "errors"
"fmt"
log "github.com/sirupsen/logrus"
@@ -18,10 +17,10 @@ import (
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
- argov1alpha1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- "github.com/argoproj/argo-cd/v3/util/argo"
- argodiff "github.com/argoproj/argo-cd/v3/util/argo/diff"
- "github.com/argoproj/argo-cd/v3/util/argo/normalizers"
+ argov1alpha1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/util/argo"
+ argodiff "github.com/argoproj/argo-cd/v2/util/argo/diff"
+ "github.com/argoproj/argo-cd/v2/util/argo/normalizers"
)
// CreateOrUpdate overrides "sigs.k8s.io/controller-runtime" function
@@ -79,10 +78,10 @@ func CreateOrUpdate(ctx context.Context, logCtx *log.Entry, c client.Client, ign
return a.Cmp(b) == 0
},
func(a, b metav1.MicroTime) bool {
- return a.UTC().Equal(b.UTC())
+ return a.UTC() == b.UTC()
},
func(a, b metav1.Time) bool {
- return a.UTC().Equal(b.UTC())
+ return a.UTC() == b.UTC()
},
func(a, b labels.Selector) bool {
return a.String() == b.String()
@@ -115,7 +114,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]any
+ var patchObj map[string]interface{}
err = json.Unmarshal(patchBytes, &patchObj)
if err != nil {
logCtx.Errorf("failed to unmarshal patch: %v", err)
@@ -129,7 +128,7 @@ func mutate(f controllerutil.MutateFn, key client.ObjectKey, obj client.Object)
return fmt.Errorf("error while wrapping using MutateFn: %w", err)
}
if newKey := client.ObjectKeyFromObject(obj); key != newKey {
- return stderrors.New("MutateFn cannot mutate object name and/or object namespace")
+ return fmt.Errorf("MutateFn cannot mutate object name and/or object namespace")
}
return nil
}
@@ -163,12 +162,12 @@ func applyIgnoreDifferences(applicationSetIgnoreDifferences argov1alpha1.Applica
if len(result.Lives) != 1 {
return fmt.Errorf("expected 1 normalized application, got %d", len(result.Lives))
}
- foundJSONNormalized, err := json.Marshal(result.Lives[0].Object)
+ foundJsonNormalized, err := json.Marshal(result.Lives[0].Object)
if err != nil {
return fmt.Errorf("failed to marshal normalized app to json: %w", err)
}
foundNormalized := &argov1alpha1.Application{}
- err = json.Unmarshal(foundJSONNormalized, &foundNormalized)
+ err = json.Unmarshal(foundJsonNormalized, &foundNormalized)
if err != nil {
return fmt.Errorf("failed to unmarshal normalized app to json: %w", err)
}
@@ -176,12 +175,12 @@ func applyIgnoreDifferences(applicationSetIgnoreDifferences argov1alpha1.Applica
return fmt.Errorf("expected 1 normalized application, got %d", len(result.Targets))
}
foundNormalized.DeepCopyInto(found)
- generatedJSONNormalized, err := json.Marshal(result.Targets[0].Object)
+ generatedJsonNormalized, err := json.Marshal(result.Targets[0].Object)
if err != nil {
return fmt.Errorf("failed to marshal normalized app to json: %w", err)
}
generatedAppNormalized := &argov1alpha1.Application{}
- err = json.Unmarshal(generatedJSONNormalized, &generatedAppNormalized)
+ err = json.Unmarshal(generatedJsonNormalized, &generatedAppNormalized)
if err != nil {
return fmt.Errorf("failed to unmarshal normalized app json to structured app: %w", err)
}
diff --git a/applicationset/utils/createOrUpdate_test.go b/applicationset/utils/createOrUpdate_test.go
index 263dbeeb69..de64541337 100644
--- a/applicationset/utils/createOrUpdate_test.go
+++ b/applicationset/utils/createOrUpdate_test.go
@@ -8,8 +8,8 @@ import (
"gopkg.in/yaml.v3"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- "github.com/argoproj/argo-cd/v3/util/argo/normalizers"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/util/argo/normalizers"
)
func Test_applyIgnoreDifferences(t *testing.T) {
diff --git a/applicationset/utils/kubernetes.go b/applicationset/utils/kubernetes.go
index b06d499b60..b5708bad2a 100644
--- a/applicationset/utils/kubernetes.go
+++ b/applicationset/utils/kubernetes.go
@@ -4,12 +4,12 @@ import (
"context"
"fmt"
- "github.com/argoproj/argo-cd/v3/common"
+ "github.com/argoproj/argo-cd/v2/common"
corev1 "k8s.io/api/core/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
- argoprojiov1alpha1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ argoprojiov1alpha1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
)
var ErrDisallowedSecretAccess = fmt.Errorf("secret must have label %q=%q", common.LabelKeySecretType, common.LabelValueSecretTypeSCMCreds)
diff --git a/applicationset/utils/kubernetes_test.go b/applicationset/utils/kubernetes_test.go
index 80c9ca5e2e..d8e86b89b0 100644
--- a/applicationset/utils/kubernetes_test.go
+++ b/applicationset/utils/kubernetes_test.go
@@ -1,6 +1,7 @@
package utils
import (
+ "context"
"testing"
"github.com/stretchr/testify/assert"
@@ -9,7 +10,7 @@ import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"sigs.k8s.io/controller-runtime/pkg/client/fake"
- argoprojiov1alpha1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ argoprojiov1alpha1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
)
func TestGetSecretRef(t *testing.T) {
@@ -20,7 +21,7 @@ func TestGetSecretRef(t *testing.T) {
},
}
client := fake.NewClientBuilder().WithObjects(secret).Build()
- ctx := t.Context()
+ ctx := context.Background()
cases := []struct {
name, namespace, token string
@@ -85,7 +86,7 @@ func TestGetConfigMapData(t *testing.T) {
},
}
client := fake.NewClientBuilder().WithObjects(configMap).Build()
- ctx := t.Context()
+ ctx := context.Background()
cases := []struct {
name, namespace, data string
diff --git a/applicationset/utils/map.go b/applicationset/utils/map.go
index 42cd39b715..0d71f20b50 100644
--- a/applicationset/utils/map.go
+++ b/applicationset/utils/map.go
@@ -4,7 +4,7 @@ import (
"fmt"
)
-func ConvertToMapStringString(mapStringInterface map[string]any) map[string]string {
+func ConvertToMapStringString(mapStringInterface map[string]interface{}) map[string]string {
mapStringString := make(map[string]string, len(mapStringInterface))
for key, value := range mapStringInterface {
@@ -13,8 +13,8 @@ func ConvertToMapStringString(mapStringInterface map[string]any) map[string]stri
return mapStringString
}
-func ConvertToMapStringInterface(mapStringString map[string]string) map[string]any {
- mapStringInterface := make(map[string]any, len(mapStringString))
+func ConvertToMapStringInterface(mapStringString map[string]string) map[string]interface{} {
+ mapStringInterface := make(map[string]interface{}, len(mapStringString))
for key, value := range mapStringString {
mapStringInterface[key] = value
@@ -22,7 +22,7 @@ func ConvertToMapStringInterface(mapStringString map[string]string) map[string]a
return mapStringInterface
}
-func CombineStringMaps(aSI map[string]any, bSI map[string]any) (map[string]string, error) {
+func CombineStringMaps(aSI map[string]interface{}, bSI map[string]interface{}) (map[string]string, error) {
a := ConvertToMapStringString(aSI)
b := ConvertToMapStringString(bSI)
@@ -44,7 +44,7 @@ func CombineStringMaps(aSI map[string]any, bSI map[string]any) (map[string]strin
}
// CombineStringMapsAllowDuplicates merges two maps. Where there are duplicates, take the latter map's value.
-func CombineStringMapsAllowDuplicates(aSI map[string]any, bSI map[string]any) (map[string]string, error) {
+func CombineStringMapsAllowDuplicates(aSI map[string]interface{}, bSI map[string]interface{}) (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 679ea356cc..c12216e0e1 100644
--- a/applicationset/utils/map_test.go
+++ b/applicationset/utils/map_test.go
@@ -1,7 +1,7 @@
package utils
import (
- "errors"
+ "fmt"
"testing"
"github.com/stretchr/testify/assert"
@@ -11,29 +11,29 @@ import (
func TestCombineStringMaps(t *testing.T) {
testCases := []struct {
name string
- left map[string]any
- right map[string]any
+ left map[string]interface{}
+ right map[string]interface{}
expected map[string]string
expectedErr error
}{
{
name: "combines the maps",
- left: map[string]any{"foo": "bar"},
- right: map[string]any{"a": "b"},
+ left: map[string]interface{}{"foo": "bar"},
+ right: map[string]interface{}{"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]any{"foo": "bar", "a": "fail"},
- right: map[string]any{"a": "b", "c": "d"},
+ left: map[string]interface{}{"foo": "bar", "a": "fail"},
+ right: map[string]interface{}{"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"),
+ expectedErr: fmt.Errorf("found duplicate key a with different value, a: fail ,b: b"),
},
{
name: "pass if keys & values are the same",
- left: map[string]any{"foo": "bar", "a": "b"},
- right: map[string]any{"a": "b", "c": "d"},
+ left: map[string]interface{}{"foo": "bar", "a": "b"},
+ right: map[string]interface{}{"a": "b", "c": "d"},
expected: map[string]string{"a": "b", "c": "d", "foo": "bar"},
expectedErr: nil,
},
diff --git a/applicationset/utils/mocks/Renderer.go b/applicationset/utils/mocks/Renderer.go
index e16665dd30..ca82e9e38b 100644
--- a/applicationset/utils/mocks/Renderer.go
+++ b/applicationset/utils/mocks/Renderer.go
@@ -1,14 +1,76 @@
-// Code generated by mockery; DO NOT EDIT.
-// github.com/vektra/mockery
-// template: testify
+// Code generated by mockery v2.53.4. DO NOT EDIT.
package mocks
import (
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
mock "github.com/stretchr/testify/mock"
+
+ v1alpha1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
)
+// Renderer is an autogenerated mock type for the Renderer type
+type Renderer struct {
+ mock.Mock
+}
+
+// RenderTemplateParams provides a mock function with given fields: tmpl, syncPolicy, params, useGoTemplate, goTemplateOptions
+func (_m *Renderer) RenderTemplateParams(tmpl *v1alpha1.Application, syncPolicy *v1alpha1.ApplicationSetSyncPolicy, params map[string]interface{}, useGoTemplate bool, goTemplateOptions []string) (*v1alpha1.Application, error) {
+ ret := _m.Called(tmpl, syncPolicy, params, useGoTemplate, goTemplateOptions)
+
+ if len(ret) == 0 {
+ panic("no return value specified for RenderTemplateParams")
+ }
+
+ var r0 *v1alpha1.Application
+ var r1 error
+ if rf, ok := ret.Get(0).(func(*v1alpha1.Application, *v1alpha1.ApplicationSetSyncPolicy, map[string]interface{}, bool, []string) (*v1alpha1.Application, error)); ok {
+ return rf(tmpl, syncPolicy, params, useGoTemplate, goTemplateOptions)
+ }
+ if rf, ok := ret.Get(0).(func(*v1alpha1.Application, *v1alpha1.ApplicationSetSyncPolicy, map[string]interface{}, bool, []string) *v1alpha1.Application); ok {
+ r0 = rf(tmpl, syncPolicy, params, useGoTemplate, goTemplateOptions)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*v1alpha1.Application)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(*v1alpha1.Application, *v1alpha1.ApplicationSetSyncPolicy, map[string]interface{}, bool, []string) error); ok {
+ r1 = rf(tmpl, syncPolicy, params, useGoTemplate, goTemplateOptions)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// Replace provides a mock function with given fields: tmpl, replaceMap, useGoTemplate, goTemplateOptions
+func (_m *Renderer) Replace(tmpl string, replaceMap map[string]interface{}, useGoTemplate bool, goTemplateOptions []string) (string, error) {
+ ret := _m.Called(tmpl, replaceMap, useGoTemplate, goTemplateOptions)
+
+ if len(ret) == 0 {
+ panic("no return value specified for Replace")
+ }
+
+ var r0 string
+ var r1 error
+ if rf, ok := ret.Get(0).(func(string, map[string]interface{}, bool, []string) (string, error)); ok {
+ return rf(tmpl, replaceMap, useGoTemplate, goTemplateOptions)
+ }
+ if rf, ok := ret.Get(0).(func(string, map[string]interface{}, bool, []string) string); ok {
+ r0 = rf(tmpl, replaceMap, useGoTemplate, goTemplateOptions)
+ } else {
+ r0 = ret.Get(0).(string)
+ }
+
+ if rf, ok := ret.Get(1).(func(string, map[string]interface{}, bool, []string) error); ok {
+ r1 = rf(tmpl, replaceMap, useGoTemplate, goTemplateOptions)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
// NewRenderer creates a new instance of Renderer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
// The first argument is typically a *testing.T value.
func NewRenderer(t interface {
@@ -22,133 +84,3 @@ func NewRenderer(t interface {
return mock
}
-
-// Renderer is an autogenerated mock type for the Renderer type
-type Renderer struct {
- mock.Mock
-}
-
-type Renderer_Expecter struct {
- mock *mock.Mock
-}
-
-func (_m *Renderer) EXPECT() *Renderer_Expecter {
- return &Renderer_Expecter{mock: &_m.Mock}
-}
-
-// RenderTemplateParams provides a mock function for the type Renderer
-func (_mock *Renderer) RenderTemplateParams(tmpl *v1alpha1.Application, syncPolicy *v1alpha1.ApplicationSetSyncPolicy, params map[string]any, useGoTemplate bool, goTemplateOptions []string) (*v1alpha1.Application, error) {
- ret := _mock.Called(tmpl, syncPolicy, params, useGoTemplate, goTemplateOptions)
-
- if len(ret) == 0 {
- panic("no return value specified for RenderTemplateParams")
- }
-
- var r0 *v1alpha1.Application
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(*v1alpha1.Application, *v1alpha1.ApplicationSetSyncPolicy, map[string]any, bool, []string) (*v1alpha1.Application, error)); ok {
- return returnFunc(tmpl, syncPolicy, params, useGoTemplate, goTemplateOptions)
- }
- if returnFunc, ok := ret.Get(0).(func(*v1alpha1.Application, *v1alpha1.ApplicationSetSyncPolicy, map[string]any, bool, []string) *v1alpha1.Application); ok {
- r0 = returnFunc(tmpl, syncPolicy, params, useGoTemplate, goTemplateOptions)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*v1alpha1.Application)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(*v1alpha1.Application, *v1alpha1.ApplicationSetSyncPolicy, map[string]any, bool, []string) error); ok {
- r1 = returnFunc(tmpl, syncPolicy, params, useGoTemplate, goTemplateOptions)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Renderer_RenderTemplateParams_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'RenderTemplateParams'
-type Renderer_RenderTemplateParams_Call struct {
- *mock.Call
-}
-
-// RenderTemplateParams is a helper method to define mock.On call
-// - tmpl
-// - syncPolicy
-// - params
-// - useGoTemplate
-// - goTemplateOptions
-func (_e *Renderer_Expecter) RenderTemplateParams(tmpl interface{}, syncPolicy interface{}, params interface{}, useGoTemplate interface{}, goTemplateOptions interface{}) *Renderer_RenderTemplateParams_Call {
- return &Renderer_RenderTemplateParams_Call{Call: _e.mock.On("RenderTemplateParams", tmpl, syncPolicy, params, useGoTemplate, goTemplateOptions)}
-}
-
-func (_c *Renderer_RenderTemplateParams_Call) Run(run func(tmpl *v1alpha1.Application, syncPolicy *v1alpha1.ApplicationSetSyncPolicy, params map[string]any, useGoTemplate bool, goTemplateOptions []string)) *Renderer_RenderTemplateParams_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(*v1alpha1.Application), args[1].(*v1alpha1.ApplicationSetSyncPolicy), args[2].(map[string]any), args[3].(bool), args[4].([]string))
- })
- return _c
-}
-
-func (_c *Renderer_RenderTemplateParams_Call) Return(application *v1alpha1.Application, err error) *Renderer_RenderTemplateParams_Call {
- _c.Call.Return(application, err)
- return _c
-}
-
-func (_c *Renderer_RenderTemplateParams_Call) RunAndReturn(run func(tmpl *v1alpha1.Application, syncPolicy *v1alpha1.ApplicationSetSyncPolicy, params map[string]any, useGoTemplate bool, goTemplateOptions []string) (*v1alpha1.Application, error)) *Renderer_RenderTemplateParams_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// Replace provides a mock function for the type Renderer
-func (_mock *Renderer) Replace(tmpl string, replaceMap map[string]any, useGoTemplate bool, goTemplateOptions []string) (string, error) {
- ret := _mock.Called(tmpl, replaceMap, useGoTemplate, goTemplateOptions)
-
- if len(ret) == 0 {
- panic("no return value specified for Replace")
- }
-
- var r0 string
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(string, map[string]any, bool, []string) (string, error)); ok {
- return returnFunc(tmpl, replaceMap, useGoTemplate, goTemplateOptions)
- }
- if returnFunc, ok := ret.Get(0).(func(string, map[string]any, bool, []string) string); ok {
- r0 = returnFunc(tmpl, replaceMap, useGoTemplate, goTemplateOptions)
- } else {
- r0 = ret.Get(0).(string)
- }
- if returnFunc, ok := ret.Get(1).(func(string, map[string]any, bool, []string) error); ok {
- r1 = returnFunc(tmpl, replaceMap, useGoTemplate, goTemplateOptions)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// Renderer_Replace_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Replace'
-type Renderer_Replace_Call struct {
- *mock.Call
-}
-
-// Replace is a helper method to define mock.On call
-// - tmpl
-// - replaceMap
-// - useGoTemplate
-// - goTemplateOptions
-func (_e *Renderer_Expecter) Replace(tmpl interface{}, replaceMap interface{}, useGoTemplate interface{}, goTemplateOptions interface{}) *Renderer_Replace_Call {
- return &Renderer_Replace_Call{Call: _e.mock.On("Replace", tmpl, replaceMap, useGoTemplate, goTemplateOptions)}
-}
-
-func (_c *Renderer_Replace_Call) Run(run func(tmpl string, replaceMap map[string]any, useGoTemplate bool, goTemplateOptions []string)) *Renderer_Replace_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(string), args[1].(map[string]any), args[2].(bool), args[3].([]string))
- })
- return _c
-}
-
-func (_c *Renderer_Replace_Call) Return(s string, err error) *Renderer_Replace_Call {
- _c.Call.Return(s, err)
- return _c
-}
-
-func (_c *Renderer_Replace_Call) RunAndReturn(run func(tmpl string, replaceMap map[string]any, useGoTemplate bool, goTemplateOptions []string) (string, error)) *Renderer_Replace_Call {
- _c.Call.Return(run)
- return _c
-}
diff --git a/applicationset/utils/policy.go b/applicationset/utils/policy.go
index cf9e6302db..a06509265a 100644
--- a/applicationset/utils/policy.go
+++ b/applicationset/utils/policy.go
@@ -1,7 +1,7 @@
package utils
import (
- argov1alpha1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ argov1alpha1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
)
// Policies is a registry of available policies.
diff --git a/applicationset/utils/selector.go b/applicationset/utils/selector.go
index eae0324236..6012fdb46f 100644
--- a/applicationset/utils/selector.go
+++ b/applicationset/utils/selector.go
@@ -6,7 +6,7 @@ import (
"strconv"
"strings"
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+ v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/selection"
"k8s.io/apimachinery/pkg/util/validation"
@@ -69,11 +69,11 @@ func (s internalSelector) Add(reqs ...Requirement) Selector {
type nothingSelector struct{}
-func (n nothingSelector) Matches(_ labels.Labels) bool {
+func (n nothingSelector) Matches(l labels.Labels) bool {
return false
}
-func (n nothingSelector) Add(_ ...Requirement) Selector {
+func (n nothingSelector) Add(r ...Requirement) Selector {
return n
}
@@ -90,7 +90,7 @@ func everything() Selector {
// LabelSelectorAsSelector converts the LabelSelector api type into a struct that implements
// labels.Selector
// Note: This function should be kept in sync with the selector methods in pkg/labels/selector.go
-func LabelSelectorAsSelector(ps *metav1.LabelSelector) (Selector, error) {
+func LabelSelectorAsSelector(ps *v1.LabelSelector) (Selector, error) {
if ps == nil {
return nothing(), nil
}
@@ -108,13 +108,13 @@ func LabelSelectorAsSelector(ps *metav1.LabelSelector) (Selector, error) {
for _, expr := range ps.MatchExpressions {
var op selection.Operator
switch expr.Operator {
- case metav1.LabelSelectorOpIn:
+ case v1.LabelSelectorOpIn:
op = selection.In
- case metav1.LabelSelectorOpNotIn:
+ case v1.LabelSelectorOpNotIn:
op = selection.NotIn
- case metav1.LabelSelectorOpExists:
+ case v1.LabelSelectorOpExists:
op = selection.Exists
- case metav1.LabelSelectorOpDoesNotExist:
+ case v1.LabelSelectorOpDoesNotExist:
op = selection.DoesNotExist
default:
return nil, fmt.Errorf("%q is not a valid pod selector operator", expr.Operator)
diff --git a/applicationset/utils/template_functions.go b/applicationset/utils/template_functions.go
index f0985cf9de..84ab870404 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 any) (string, error) {
+func toYAML(v interface{}) (string, error) {
data, err := yaml.Marshal(v)
if err != nil {
// Swallow errors inside of a template.
@@ -39,14 +39,14 @@ func toYAML(v any) (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]any.
+// fromYAML converts a YAML document into a map[string]interface{}.
//
// 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]any, error) {
- m := map[string]any{}
+func fromYAML(str string) (map[string]interface{}, error) {
+ m := map[string]interface{}{}
if err := yaml.Unmarshal([]byte(str), &m); err != nil {
return nil, err
@@ -55,14 +55,14 @@ func fromYAML(str string) (map[string]any, 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 []any.
+// fromYAMLArray converts a YAML array into a []interface{}.
//
// 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) ([]any, error) {
- a := []any{}
+func fromYAMLArray(str string) ([]interface{}, error) {
+ a := []interface{}{}
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 368fcbb6c9..4122dee28a 100644
--- a/applicationset/utils/utils.go
+++ b/applicationset/utils/utils.go
@@ -5,7 +5,6 @@ import (
"crypto/tls"
"crypto/x509"
"encoding/json"
- "errors"
"fmt"
"io"
"os"
@@ -23,8 +22,8 @@ import (
log "github.com/sirupsen/logrus"
- argoappsv1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- "github.com/argoproj/argo-cd/v3/util/glob"
+ argoappsv1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/util/glob"
)
var sprigFuncMap = sprig.GenericFuncMap() // a singleton for better performance
@@ -42,8 +41,8 @@ func init() {
}
type Renderer interface {
- 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)
+ 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)
}
type Render struct{}
@@ -81,7 +80,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]any, useGoTemplate bool, goTemplateOptions []string) error {
+func (r *Render) deeplyReplace(copy, original reflect.Value, replaceMap map[string]interface{}, 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
@@ -131,19 +130,19 @@ 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++ {
+ for i := 0; i < original.NumField(); i += 1 {
currentType := fmt.Sprintf("%s.%s", original.Type().Field(i).Name, original.Type().PkgPath())
// specific case time
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 any
+ var unmarshaled interface{}
originalBytes := original.Field(i).Bytes()
- convertedToJSON, err := ConvertYAMLToJSON(string(originalBytes))
+ convertedToJson, err := ConvertYAMLToJSON(string(originalBytes))
if err != nil {
- return fmt.Errorf("error while converting template to json %q: %w", convertedToJSON, err)
+ return fmt.Errorf("error while converting template to json %q: %w", convertedToJson, err)
}
- err = json.Unmarshal([]byte(convertedToJSON), &unmarshaled)
+ err = json.Unmarshal([]byte(convertedToJson), &unmarshaled)
if err != nil {
return fmt.Errorf("failed to unmarshal JSON field: %w", err)
}
@@ -153,7 +152,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().(*any)
+ jsonCopyInterface := jsonCopy.Interface().(*interface{})
data, err := json.Marshal(jsonCopyInterface)
if err != nil {
return fmt.Errorf("failed to marshal templated JSON field: %w", err)
@@ -173,7 +172,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++ {
+ for i := 0; i < original.Len(); i += 1 {
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
@@ -250,9 +249,9 @@ func isNillable(v reflect.Value) bool {
return false
}
-func (r *Render) RenderTemplateParams(tmpl *argoappsv1.Application, syncPolicy *argoappsv1.ApplicationSetSyncPolicy, params map[string]any, useGoTemplate bool, goTemplateOptions []string) (*argoappsv1.Application, error) {
+func (r *Render) RenderTemplateParams(tmpl *argoappsv1.Application, syncPolicy *argoappsv1.ApplicationSetSyncPolicy, params map[string]interface{}, useGoTemplate bool, goTemplateOptions []string) (*argoappsv1.Application, error) {
if tmpl == nil {
- return nil, errors.New("application template is empty")
+ return nil, fmt.Errorf("application template is empty")
}
if len(params) == 0 {
@@ -274,16 +273,16 @@ func (r *Render) RenderTemplateParams(tmpl *argoappsv1.Application, syncPolicy *
// b) there IS a syncPolicy, but preserveResourcesOnDeletion is set to false
// See TestRenderTemplateParamsFinalizers in util_test.go for test-based definition of behaviour
if (syncPolicy == nil || !syncPolicy.PreserveResourcesOnDeletion) &&
- len(replacedTmpl.Finalizers) == 0 {
- replacedTmpl.Finalizers = []string{"resources-finalizer.argocd.argoproj.io"}
+ len(replacedTmpl.ObjectMeta.Finalizers) == 0 {
+ replacedTmpl.ObjectMeta.Finalizers = []string{"resources-finalizer.argocd.argoproj.io"}
}
return replacedTmpl, nil
}
-func (r *Render) RenderGeneratorParams(gen *argoappsv1.ApplicationSetGenerator, params map[string]any, useGoTemplate bool, goTemplateOptions []string) (*argoappsv1.ApplicationSetGenerator, error) {
+func (r *Render) RenderGeneratorParams(gen *argoappsv1.ApplicationSetGenerator, params map[string]interface{}, useGoTemplate bool, goTemplateOptions []string) (*argoappsv1.ApplicationSetGenerator, error) {
if gen == nil {
- return nil, errors.New("generator is empty")
+ return nil, fmt.Errorf("generator is empty")
}
if len(params) == 0 {
@@ -306,7 +305,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]any, useGoTemplate bool, goTemplateOptions []string) (string, error) {
+func (r *Render) Replace(tmpl string, replaceMap map[string]interface{}, useGoTemplate bool, goTemplateOptions []string) (string, error) {
if useGoTemplate {
template, err := template.New("").Funcs(sprigFuncMap).Parse(tmpl)
if err != nil {
@@ -336,7 +335,7 @@ func (r *Render) Replace(tmpl string, replaceMap map[string]any, useGoTemplate b
trimmedTag := strings.TrimSpace(tag)
replacement, ok := replaceMap[trimmedTag].(string)
if len(trimmedTag) == 0 || !ok {
- return fmt.Fprintf(w, "{{%s}}", tag)
+ return w.Write([]byte(fmt.Sprintf("{{%s}}", tag)))
}
return w.Write([]byte(replacement))
})
@@ -353,12 +352,12 @@ func CheckInvalidGenerators(applicationSetInfo *argoappsv1.ApplicationSet) error
gnames = append(gnames, n)
}
sort.Strings(gnames)
- aname := applicationSetInfo.Name
+ aname := applicationSetInfo.ObjectMeta.Name
msg := "ApplicationSet %s contains unrecognized generators: %s"
errorMessage = fmt.Errorf(msg, aname, strings.Join(gnames, ", "))
log.Warnf(msg, aname, strings.Join(gnames, ", "))
} else if hasInvalidGenerators {
- name := applicationSetInfo.Name
+ name := applicationSetInfo.ObjectMeta.Name
msg := "ApplicationSet %s contains unrecognized generators"
errorMessage = fmt.Errorf(msg, name)
log.Warnf(msg, name)
@@ -394,21 +393,21 @@ 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.Annotations["kubectl.kubernetes.io/last-applied-configuration"]
- var values map[string]any
+ config := applicationSetInfo.ObjectMeta.Annotations["kubectl.kubernetes.io/last-applied-configuration"]
+ var values map[string]interface{}
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]any)
+ spec, ok := values["spec"].(map[string]interface{})
if !ok {
log.Warn("coundn't get spec from kubectl.kubernetes.io/last-applied-configuration annotation")
return
}
- generators, ok := spec["generators"].([]any)
+ generators, ok := spec["generators"].([]interface{})
if !ok {
log.Warn("coundn't get generators from kubectl.kubernetes.io/last-applied-configuration annotation")
return
@@ -419,7 +418,7 @@ func addInvalidGeneratorNames(names map[string]bool, applicationSetInfo *argoapp
return
}
- generator, ok := generators[index].(map[string]any)
+ generator, ok := generators[index].(map[string]interface{})
if !ok {
log.Warn("coundn't get generator from kubectl.kubernetes.io/last-applied-configuration annotation")
return
@@ -457,7 +456,7 @@ func NormalizeBitbucketBasePath(basePath string) string {
//
// Returns:
// - string: The generated URL-friendly slug based on the input name and options.
-func SlugifyName(args ...any) string {
+func SlugifyName(args ...interface{}) string {
// Default values for arguments
maxSize := 50
EnableSmartTruncate := true
@@ -489,7 +488,7 @@ func SlugifyName(args ...any) string {
return urlSlug
}
-func getTLSConfigWithCACert(scmRootCAPath string, caCerts []byte) *tls.Config {
+func getTlsConfigWithCACert(scmRootCAPath string, caCerts []byte) *tls.Config {
tlsConfig := &tls.Config{}
if scmRootCAPath != "" {
@@ -518,8 +517,8 @@ func getTLSConfigWithCACert(scmRootCAPath string, caCerts []byte) *tls.Config {
return tlsConfig
}
-func GetTlsConfig(scmRootCAPath string, insecure bool, caCerts []byte) *tls.Config { //nolint:revive //FIXME(var-naming)
- tlsConfig := getTLSConfigWithCACert(scmRootCAPath, caCerts)
+func GetTlsConfig(scmRootCAPath string, insecure bool, caCerts []byte) *tls.Config {
+ tlsConfig := getTlsConfigWithCACert(scmRootCAPath, caCerts)
if insecure {
tlsConfig.InsecureSkipVerify = true
diff --git a/applicationset/utils/utils_test.go b/applicationset/utils/utils_test.go
index 351d144e2f..8d19a2cffa 100644
--- a/applicationset/utils/utils_test.go
+++ b/applicationset/utils/utils_test.go
@@ -17,7 +17,7 @@ import (
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
- argoappsv1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ argoappsv1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
)
func TestRenderTemplateParams(t *testing.T) {
@@ -62,14 +62,14 @@ func TestRenderTemplateParams(t *testing.T) {
tests := []struct {
name string
fieldVal string
- params map[string]any
+ params map[string]interface{}
expectedVal string
}{
{
name: "simple substitution",
fieldVal: "{{one}}",
expectedVal: "two",
- params: map[string]any{
+ params: map[string]interface{}{
"one": "two",
},
},
@@ -77,7 +77,7 @@ func TestRenderTemplateParams(t *testing.T) {
name: "simple substitution with whitespace",
fieldVal: "{{ one }}",
expectedVal: "two",
- params: map[string]any{
+ params: map[string]interface{}{
"one": "two",
},
},
@@ -86,7 +86,7 @@ func TestRenderTemplateParams(t *testing.T) {
name: "template characters but not in a template",
fieldVal: "}} {{",
expectedVal: "}} {{",
- params: map[string]any{
+ params: map[string]interface{}{
"one": "two",
},
},
@@ -95,7 +95,7 @@ func TestRenderTemplateParams(t *testing.T) {
name: "nested template",
fieldVal: "{{ }}",
expectedVal: "{{ }}",
- params: map[string]any{
+ params: map[string]interface{}{
"one": "{{ }}",
},
},
@@ -103,7 +103,7 @@ func TestRenderTemplateParams(t *testing.T) {
name: "field with whitespace",
fieldVal: "{{ }}",
expectedVal: "{{ }}",
- params: map[string]any{
+ params: map[string]interface{}{
" ": "two",
"": "three",
},
@@ -113,7 +113,7 @@ func TestRenderTemplateParams(t *testing.T) {
name: "template contains itself, containing itself",
fieldVal: "{{one}}",
expectedVal: "{{one}}",
- params: map[string]any{
+ params: map[string]interface{}{
"{{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]any{
+ params: map[string]interface{}{
"{{one}}": "{{two}}",
},
},
@@ -131,7 +131,7 @@ func TestRenderTemplateParams(t *testing.T) {
name: "templates are case sensitive",
fieldVal: "{{ONE}}",
expectedVal: "{{ONE}}",
- params: map[string]any{
+ params: map[string]interface{}{
"{{one}}": "two",
},
},
@@ -139,7 +139,7 @@ func TestRenderTemplateParams(t *testing.T) {
name: "multiple on a line",
fieldVal: "{{one}}{{one}}",
expectedVal: "twotwo",
- params: map[string]any{
+ params: map[string]interface{}{
"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]any{
+ params: map[string]interface{}{
"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]any{
+ params: map[string]interface{}{
"one": "\"hello\" world",
"three": "four",
},
@@ -180,14 +180,14 @@ func TestRenderTemplateParams(t *testing.T) {
// the target field has been templated into the expected value
actualValue := *getPtrFunc(newApplication)
assert.Equal(t, test.expectedVal, actualValue, "Field '%s' had an unexpected value. expected: '%s' value: '%s'", fieldName, test.expectedVal, actualValue)
- assert.Equal(t, "annotation-value", newApplication.Annotations["annotation-key"])
- assert.Equal(t, "annotation-value2", newApplication.Annotations["annotation-key2"])
- assert.Equal(t, "label-value", newApplication.Labels["label-key"])
- assert.Equal(t, "label-value2", newApplication.Labels["label-key2"])
- assert.Equal(t, "application-one", newApplication.Name)
- assert.Equal(t, "default", newApplication.Namespace)
- assert.Equal(t, newApplication.UID, types.UID("d546da12-06b7-4f9a-8ea2-3adb16a20e2b"))
- assert.Equal(t, newApplication.CreationTimestamp, application.CreationTimestamp)
+ assert.Equal(t, "annotation-value", newApplication.ObjectMeta.Annotations["annotation-key"])
+ assert.Equal(t, "annotation-value2", newApplication.ObjectMeta.Annotations["annotation-key2"])
+ assert.Equal(t, "label-value", newApplication.ObjectMeta.Labels["label-key"])
+ assert.Equal(t, "label-value2", newApplication.ObjectMeta.Labels["label-key2"])
+ assert.Equal(t, "application-one", newApplication.ObjectMeta.Name)
+ assert.Equal(t, "default", newApplication.ObjectMeta.Namespace)
+ assert.Equal(t, newApplication.ObjectMeta.UID, types.UID("d546da12-06b7-4f9a-8ea2-3adb16a20e2b"))
+ assert.Equal(t, newApplication.ObjectMeta.CreationTimestamp, application.ObjectMeta.CreationTimestamp)
require.NoError(t, err)
}
})
@@ -195,7 +195,7 @@ func TestRenderTemplateParams(t *testing.T) {
}
func TestRenderHelmValuesObjectJson(t *testing.T) {
- params := map[string]any{
+ params := map[string]interface{}{
"test": "Hello world",
}
@@ -240,15 +240,15 @@ func TestRenderHelmValuesObjectJson(t *testing.T) {
require.NoError(t, err)
assert.NotNil(t, newApplication)
- var unmarshaled any
+ var unmarshaled interface{}
err = json.Unmarshal(newApplication.Spec.Source.Helm.ValuesObject.Raw, &unmarshaled)
require.NoError(t, err)
- assert.Equal(t, "Hello world", unmarshaled.(map[string]any)["some"].(map[string]any)["string"])
+ assert.Equal(t, "Hello world", unmarshaled.(map[string]interface{})["some"].(map[string]interface{})["string"])
}
func TestRenderHelmValuesObjectYaml(t *testing.T) {
- params := map[string]any{
+ params := map[string]interface{}{
"test": "Hello world",
}
@@ -290,11 +290,11 @@ func TestRenderHelmValuesObjectYaml(t *testing.T) {
require.NoError(t, err)
assert.NotNil(t, newApplication)
- var unmarshaled any
+ var unmarshaled interface{}
err = json.Unmarshal(newApplication.Spec.Source.Helm.ValuesObject.Raw, &unmarshaled)
require.NoError(t, err)
- assert.Equal(t, "Hello world", unmarshaled.(map[string]any)["some"].(map[string]any)["string"])
+ assert.Equal(t, "Hello world", unmarshaled.(map[string]interface{})["some"].(map[string]interface{})["string"])
}
func TestRenderTemplateParamsGoTemplate(t *testing.T) {
@@ -339,7 +339,7 @@ func TestRenderTemplateParamsGoTemplate(t *testing.T) {
tests := []struct {
name string
fieldVal string
- params map[string]any
+ params map[string]interface{}
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]any{
+ params: map[string]interface{}{
"one": "two",
},
},
@@ -356,7 +356,7 @@ func TestRenderTemplateParamsGoTemplate(t *testing.T) {
name: "simple substitution with whitespace",
fieldVal: "{{ .one }}",
expectedVal: "two",
- params: map[string]any{
+ params: map[string]interface{}{
"one": "two",
},
},
@@ -364,7 +364,7 @@ func TestRenderTemplateParamsGoTemplate(t *testing.T) {
name: "template contains itself, containing itself",
fieldVal: "{{ .one }}",
expectedVal: "{{one}}",
- params: map[string]any{
+ params: map[string]interface{}{
"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]any{
+ params: map[string]interface{}{
"one": "{{two}}",
},
},
@@ -381,7 +381,7 @@ func TestRenderTemplateParamsGoTemplate(t *testing.T) {
name: "multiple on a line",
fieldVal: "{{.one}}{{.one}}",
expectedVal: "twotwo",
- params: map[string]any{
+ params: map[string]interface{}{
"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]any{
+ params: map[string]interface{}{
"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]any{
+ params: map[string]interface{}{
"one": "\"hello\" world",
"three": "four",
},
@@ -407,9 +407,9 @@ func TestRenderTemplateParamsGoTemplate(t *testing.T) {
name: "depth",
fieldVal: "{{ .image.version }}",
expectedVal: "latest",
- params: map[string]any{
+ params: map[string]interface{}{
"replicas": 3,
- "image": map[string]any{
+ "image": map[string]interface{}{
"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]any{
+ params: map[string]interface{}{
"replicas": 3,
- "image": map[string]any{
+ "image": map[string]interface{}{
"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]any{
+ params: map[string]interface{}{
"replicas": 3,
- "hpa": map[string]any{
+ "hpa": map[string]interface{}{
"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]any{
+ params: map[string]interface{}{
"replicas": 3,
- "hpa": map[string]any{
+ "hpa": map[string]interface{}{
"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]any{
+ params: map[string]interface{}{
"replicas": 3,
- "volumes": []map[string]any{
+ "volumes": []map[string]interface{}{
{
"name": "volume-one",
- "emptyDir": map[string]any{},
+ "emptyDir": map[string]interface{}{},
},
{
"name": "volume-two",
- "emptyDir": map[string]any{},
+ "emptyDir": map[string]interface{}{},
},
},
},
@@ -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]any{
- "admin": map[string]any{
+ params: map[string]interface{}{
+ "admin": map[string]interface{}{
"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]any{
- "admin": map[string]any{
+ params: map[string]interface{}{
+ "admin": map[string]interface{}{
"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]any{
+ params: map[string]interface{}{
"quote": `"`,
},
},
@@ -505,13 +505,13 @@ func TestRenderTemplateParamsGoTemplate(t *testing.T) {
name: "Test No Data",
fieldVal: `{{.data}}`,
expectedVal: "{{.data}}",
- params: map[string]any{},
+ params: map[string]interface{}{},
},
{
name: "Test Parse Error",
fieldVal: `{{functiondoesnotexist}}`,
expectedVal: "",
- params: map[string]any{
+ params: map[string]interface{}{
"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]any{
+ params: map[string]interface{}{
"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]any{
+ params: map[string]interface{}{
// 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]any{
+ params: map[string]interface{}{
// 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]any{
- "foo": map[string]any{
- "bar": map[string]any{
+ params: map[string]interface{}{
+ "foo": map[string]interface{}{
+ "bar": map[string]interface{}{
"bool": true,
"number": 2,
"str": "Hello world",
@@ -564,8 +564,8 @@ 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]any{
- "foo": func(_ *string) {
+ params: map[string]interface{}{
+ "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]any{
+ params: map[string]interface{}{
"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]any{
+ params: map[string]interface{}{
"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]any{
+ params: map[string]interface{}{
"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]any{
+ params: map[string]interface{}{
"value": "non\n compliant\n yaml",
},
},
@@ -627,14 +627,14 @@ func TestRenderTemplateParamsGoTemplate(t *testing.T) {
require.NoError(t, err)
actualValue := *getPtrFunc(newApplication)
assert.Equal(t, test.expectedVal, actualValue, "Field '%s' had an unexpected value. expected: '%s' value: '%s'", fieldName, test.expectedVal, actualValue)
- assert.Equal(t, "annotation-value", newApplication.Annotations["annotation-key"])
- assert.Equal(t, "annotation-value2", newApplication.Annotations["annotation-key2"])
- assert.Equal(t, "label-value", newApplication.Labels["label-key"])
- assert.Equal(t, "label-value2", newApplication.Labels["label-key2"])
- assert.Equal(t, "application-one", newApplication.Name)
- assert.Equal(t, "default", newApplication.Namespace)
- assert.Equal(t, newApplication.UID, types.UID("d546da12-06b7-4f9a-8ea2-3adb16a20e2b"))
- assert.Equal(t, newApplication.CreationTimestamp, application.CreationTimestamp)
+ assert.Equal(t, "annotation-value", newApplication.ObjectMeta.Annotations["annotation-key"])
+ assert.Equal(t, "annotation-value2", newApplication.ObjectMeta.Annotations["annotation-key2"])
+ assert.Equal(t, "label-value", newApplication.ObjectMeta.Labels["label-key"])
+ assert.Equal(t, "label-value2", newApplication.ObjectMeta.Labels["label-key2"])
+ assert.Equal(t, "application-one", newApplication.ObjectMeta.Name)
+ assert.Equal(t, "default", newApplication.ObjectMeta.Namespace)
+ assert.Equal(t, newApplication.ObjectMeta.UID, types.UID("d546da12-06b7-4f9a-8ea2-3adb16a20e2b"))
+ assert.Equal(t, newApplication.ObjectMeta.CreationTimestamp, application.ObjectMeta.CreationTimestamp)
}
}
})
@@ -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]any{
+ params := map[string]interface{}{
"branch": "master",
}
generator := &argoappsv1.ApplicationSetGenerator{
@@ -679,7 +679,7 @@ func TestRenderTemplateKeys(t *testing.T) {
},
}
- params := map[string]any{
+ params := map[string]interface{}{
"key": "some-key",
"value": "some-value",
}
@@ -687,8 +687,8 @@ func TestRenderTemplateKeys(t *testing.T) {
render := Render{}
newApplication, err := render.RenderTemplateParams(application, nil, params, false, nil)
require.NoError(t, err)
- require.Contains(t, newApplication.Annotations, "annotation-some-key")
- assert.Equal(t, "annotation-some-value", newApplication.Annotations["annotation-some-key"])
+ require.Contains(t, newApplication.ObjectMeta.Annotations, "annotation-some-key")
+ assert.Equal(t, "annotation-some-value", newApplication.ObjectMeta.Annotations["annotation-some-key"])
})
t.Run("gotemplate", func(t *testing.T) {
application := &argoappsv1.Application{
@@ -699,7 +699,7 @@ func TestRenderTemplateKeys(t *testing.T) {
},
}
- params := map[string]any{
+ params := map[string]interface{}{
"key": "some-key",
"value": "some-value",
}
@@ -707,8 +707,8 @@ func TestRenderTemplateKeys(t *testing.T) {
render := Render{}
newApplication, err := render.RenderTemplateParams(application, nil, params, true, nil)
require.NoError(t, err)
- require.Contains(t, newApplication.Annotations, "annotation-some-key")
- assert.Equal(t, "annotation-some-value", newApplication.Annotations["annotation-some-key"])
+ require.Contains(t, newApplication.ObjectMeta.Annotations, "annotation-some-key")
+ assert.Equal(t, "annotation-some-value", newApplication.ObjectMeta.Annotations["annotation-some-key"])
})
}
@@ -804,7 +804,7 @@ func TestRenderTemplateParamsFinalizers(t *testing.T) {
application := emptyApplication.DeepCopy()
application.Finalizers = c.existingFinalizers
- params := map[string]any{
+ params := map[string]interface{}{
"one": "two",
}
@@ -1331,42 +1331,42 @@ WkBKOclmOV2xlTVuPw==
scmRootCAPath string
insecure bool
caCerts []byte
- validateCertInTLSConfig bool
+ validateCertInTlsConfig bool
}{
{
name: "Insecure mode configured, SCM Root CA Path not set",
scmRootCAPath: "",
insecure: true,
caCerts: nil,
- validateCertInTLSConfig: false,
+ validateCertInTlsConfig: false,
},
{
name: "SCM Root CA Path set, Insecure mode set to false",
scmRootCAPath: rootCAPath,
insecure: false,
caCerts: nil,
- validateCertInTLSConfig: true,
+ validateCertInTlsConfig: true,
},
{
name: "SCM Root CA Path set, Insecure mode set to true",
scmRootCAPath: rootCAPath,
insecure: true,
caCerts: nil,
- validateCertInTLSConfig: true,
+ validateCertInTlsConfig: true,
},
{
name: "Cert passed, Insecure mode set to false",
scmRootCAPath: "",
insecure: false,
caCerts: []byte(certFromCM),
- validateCertInTLSConfig: true,
+ validateCertInTlsConfig: true,
},
{
name: "SCM Root CA Path set, cert passed, Insecure mode set to false",
scmRootCAPath: rootCAPath,
insecure: false,
caCerts: []byte(certFromCM),
- validateCertInTLSConfig: true,
+ validateCertInTlsConfig: true,
},
}
@@ -1384,7 +1384,7 @@ WkBKOclmOV2xlTVuPw==
assert.True(t, ok)
}
assert.NotNil(t, tlsConfig)
- if testCase.validateCertInTLSConfig {
+ if testCase.validateCertInTlsConfig {
assert.True(t, tlsConfig.RootCAs.Equal(certPool))
}
})
diff --git a/applicationset/webhook/testdata/gitlab-event.json b/applicationset/webhook/testdata/gitlab-event.json
index 9371005e18..83ac0b4fcb 100644
--- a/applicationset/webhook/testdata/gitlab-event.json
+++ b/applicationset/webhook/testdata/gitlab-event.json
@@ -1,65 +1,65 @@
{
- "object_kind": "push",
- "event_name": "push",
- "before": "e5ba5f6c13b64670048daa88e4c053d60b0e115a",
- "after": "bb0748feaa336d841c251017e4e374c22d0c8a98",
- "ref": "refs/heads/master",
- "checkout_sha": "bb0748feaa336d841c251017e4e374c22d0c8a98",
- "message": null,
- "user_id": 1,
- "user_name": "name",
- "user_username": "username",
- "user_email": "",
- "user_avatar": "",
- "project_id": 1,
- "project": {
- "id": 1,
- "name": "project",
- "description": "",
- "web_url": "https://gitlab.com/group/name",
- "avatar_url": null,
- "git_ssh_url": "ssh://git@gitlab.com:2222/group/name.git",
- "git_http_url": "https://gitlab.com/group/name.git",
- "namespace": "group",
- "visibility_level": 1,
- "path_with_namespace": "group/name",
- "default_branch": "master",
- "ci_config_path": null,
- "homepage": "https://gitlab.com/group/name",
- "url": "ssh://git@gitlab.com:2222/group/name.git",
- "ssh_url": "ssh://git@gitlab.com:2222/group/name.git",
- "http_url": "https://gitlab.com/group/name.git"
- },
- "commits": [
- {
- "id": "bb0748feaa336d841c251017e4e374c22d0c8a98",
- "message": "Test commit message\n",
- "timestamp": "2020-01-06T03:47:55Z",
- "url": "https://gitlab.com/group/name/commit/bb0748feaa336d841c251017e4e374c22d0c8a98",
- "author": {
- "name": "User",
- "email": "user@example.com"
- },
- "added": [
- "file.yaml"
- ],
- "modified": [
- ],
- "removed": [
-
- ]
+ "object_kind": "push",
+ "event_name": "push",
+ "before": "e5ba5f6c13b64670048daa88e4c053d60b0e115a",
+ "after": "bb0748feaa336d841c251017e4e374c22d0c8a98",
+ "ref": "refs/heads/master",
+ "checkout_sha": "bb0748feaa336d841c251017e4e374c22d0c8a98",
+ "message": null,
+ "user_id": 1,
+ "user_name": "name",
+ "user_username": "username",
+ "user_email": "",
+ "user_avatar": "",
+ "project_id": 1,
+ "project": {
+ "id": 1,
+ "name": "project",
+ "description": "",
+ "web_url": "https://gitlab/group/name",
+ "avatar_url": null,
+ "git_ssh_url": "ssh://git@gitlab:2222/group/name.git",
+ "git_http_url": "https://gitlab/group/name.git",
+ "namespace": "group",
+ "visibility_level": 1,
+ "path_with_namespace": "group/name",
+ "default_branch": "master",
+ "ci_config_path": null,
+ "homepage": "https://gitlab/group/name",
+ "url": "ssh://git@gitlab:2222/group/name.git",
+ "ssh_url": "ssh://git@gitlab:2222/group/name.git",
+ "http_url": "https://gitlab/group/name.git"
+ },
+ "commits": [
+ {
+ "id": "bb0748feaa336d841c251017e4e374c22d0c8a98",
+ "message": "Test commit message\n",
+ "timestamp": "2020-01-06T03:47:55Z",
+ "url": "https://gitlab/group/name/commit/bb0748feaa336d841c251017e4e374c22d0c8a98",
+ "author": {
+ "name": "User",
+ "email": "user@example.com"
+ },
+ "added": [
+ "file.yaml"
+ ],
+ "modified": [
+ ],
+ "removed": [
+
+ ]
+ }
+ ],
+ "total_commits_count": 1,
+ "push_options": {
+ },
+ "repository": {
+ "name": "name",
+ "url": "ssh://git@gitlab:2222/group/name.git",
+ "description": "",
+ "homepage": "https://gitlab/group/name",
+ "git_http_url": "https://gitlab/group/name.git",
+ "git_ssh_url": "ssh://git@gitlab:2222/group/name.git",
+ "visibility_level": 10
}
- ],
- "total_commits_count": 1,
- "push_options": {
- },
- "repository": {
- "name": "name",
- "url": "ssh://git@gitlab.com:2222/group/name.git",
- "description": "",
- "homepage": "https://gitlab.com/group/name",
- "git_http_url": "https://gitlab.com/group/name.git",
- "git_ssh_url": "ssh://git@gitlab.com:2222/group/name.git",
- "visibility_level": 10
- }
-}
+ }
\ No newline at end of file
diff --git a/applicationset/webhook/testdata/gitlab-merge-request-approval-event.json b/applicationset/webhook/testdata/gitlab-merge-request-approval-event.json
index f7137298a1..bef2fee493 100644
--- a/applicationset/webhook/testdata/gitlab-merge-request-approval-event.json
+++ b/applicationset/webhook/testdata/gitlab-merge-request-approval-event.json
@@ -14,7 +14,7 @@
"description": "",
"web_url": "https://gitlab.com/group/name",
"avatar_url": null,
- "git_ssh_url": "ssh://git@gitlab.com:2222/group/name.git",
+ "git_ssh_url": "ssh://git@gitlab:2222/group/name.git",
"git_http_url": "https://gitlab.com/group/name.git",
"namespace": "group",
"visibility_level": 1,
@@ -22,17 +22,17 @@
"default_branch": "master",
"ci_config_path": null,
"homepage": "https://gitlab.com/group/name",
- "url": "ssh://git@gitlab.com:2222/group/name.git",
- "ssh_url": "ssh://git@gitlab.com:2222/group/name.git",
+ "url": "ssh://git@gitlab:2222/group/name.git",
+ "ssh_url": "ssh://git@gitlab:2222/group/name.git",
"http_url": "https://gitlab.com/group/name.git"
},
"repository": {
"name": "name",
- "url": "ssh://git@gitlab.com:2222/group/name.git",
+ "url": "ssh://git@gitlab:2222/group/name.git",
"description": "",
"homepage": "https://gitlab.com/group/name",
"git_http_url": "https://gitlab.com/group/name.git",
- "git_ssh_url": "ssh://git@gitlab.com:2222/group/name.git",
+ "git_ssh_url": "ssh://git@gitlab:2222/group/name.git",
"visibility_level": 10
},
"object_attributes": {
@@ -60,7 +60,7 @@
"description": "Aut reprehenderit ut est.",
"web_url": "https://gitlab.com/group/name",
"avatar_url": null,
- "git_ssh_url": "ssh://git@gitlab.com:2222/group/name.git",
+ "git_ssh_url": "ssh://git@gitlab:2222/group/name.git",
"git_http_url": "https://gitlab.com/group/name.git",
"namespace": "Awesome Space",
"visibility_level": 20,
@@ -68,7 +68,7 @@
"default_branch": "master",
"homepage": "https://gitlab.com/group/name",
"url": "https://gitlab.com/group/name.git",
- "ssh_url": "ssh://git@gitlab.com:2222/group/name.git",
+ "ssh_url": "ssh://git@gitlab:2222/group/name.git",
"http_url": "https://gitlab.com/group/name.git"
},
"target": {
@@ -76,7 +76,7 @@
"description": "Aut reprehenderit ut est.",
"web_url": "https://gitlab.com/group/name",
"avatar_url": null,
- "git_ssh_url": "ssh://git@gitlab.com:2222/group/name.git",
+ "git_ssh_url": "ssh://git@gitlab:2222/group/name.git",
"git_http_url": "https://gitlab.com/group/name.git",
"namespace": "Awesome Space",
"visibility_level": 20,
@@ -84,7 +84,7 @@
"default_branch": "master",
"homepage": "https://gitlab.com/group/name",
"url": "https://gitlab.com/group/name.git",
- "ssh_url": "ssh://git@gitlab.com:2222/group/name.git",
+ "ssh_url": "ssh://git@gitlab:2222/group/name.git",
"http_url": "https://gitlab.com/group/name.git"
},
"last_commit": {
diff --git a/applicationset/webhook/testdata/gitlab-merge-request-open-event.json b/applicationset/webhook/testdata/gitlab-merge-request-open-event.json
index 953ac8d366..e4e226a46d 100644
--- a/applicationset/webhook/testdata/gitlab-merge-request-open-event.json
+++ b/applicationset/webhook/testdata/gitlab-merge-request-open-event.json
@@ -14,7 +14,7 @@
"description": "",
"web_url": "https://gitlab.com/group/name",
"avatar_url": null,
- "git_ssh_url": "ssh://git@gitlab.com:2222/group/name.git",
+ "git_ssh_url": "ssh://git@gitlab:2222/group/name.git",
"git_http_url": "https://gitlab.com/group/name.git",
"namespace": "group",
"visibility_level": 1,
@@ -22,17 +22,17 @@
"default_branch": "master",
"ci_config_path": null,
"homepage": "https://gitlab.com/group/name",
- "url": "ssh://git@gitlab.com:2222/group/name.git",
- "ssh_url": "ssh://git@gitlab.com:2222/group/name.git",
+ "url": "ssh://git@gitlab:2222/group/name.git",
+ "ssh_url": "ssh://git@gitlab:2222/group/name.git",
"http_url": "https://gitlab.com/group/name.git"
},
"repository": {
"name": "name",
- "url": "ssh://git@gitlab.com:2222/group/name.git",
+ "url": "ssh://git@gitlab:2222/group/name.git",
"description": "",
"homepage": "https://gitlab.com/group/name",
"git_http_url": "https://gitlab.com/group/name.git",
- "git_ssh_url": "ssh://git@gitlab.com:2222/group/name.git",
+ "git_ssh_url": "ssh://git@gitlab:2222/group/name.git",
"visibility_level": 10
},
"object_attributes": {
@@ -60,7 +60,7 @@
"description": "Aut reprehenderit ut est.",
"web_url": "https://gitlab.com/group/name",
"avatar_url": null,
- "git_ssh_url": "ssh://git@gitlab.com:2222/group/name.git",
+ "git_ssh_url": "ssh://git@gitlab:2222/group/name.git",
"git_http_url": "https://gitlab.com/group/name.git",
"namespace": "Awesome Space",
"visibility_level": 20,
@@ -68,7 +68,7 @@
"default_branch": "master",
"homepage": "https://gitlab.com/group/name",
"url": "https://gitlab.com/group/name.git",
- "ssh_url": "ssh://git@gitlab.com:2222/group/name.git",
+ "ssh_url": "ssh://git@gitlab:2222/group/name.git",
"http_url": "https://gitlab.com/group/name.git"
},
"target": {
@@ -76,7 +76,7 @@
"description": "Aut reprehenderit ut est.",
"web_url": "https://gitlab.com/group/name",
"avatar_url": null,
- "git_ssh_url": "ssh://git@gitlab.com:2222/group/name.git",
+ "git_ssh_url": "ssh://git@gitlab:2222/group/name.git",
"git_http_url": "https://gitlab.com/group/name.git",
"namespace": "Awesome Space",
"visibility_level": 20,
@@ -84,7 +84,7 @@
"default_branch": "master",
"homepage": "https://gitlab.com/group/name",
"url": "https://gitlab.com/group/name.git",
- "ssh_url": "ssh://git@gitlab.com:2222/group/name.git",
+ "ssh_url": "ssh://git@gitlab:2222/group/name.git",
"http_url": "https://gitlab.com/group/name.git"
},
"last_commit": {
diff --git a/applicationset/webhook/webhook.go b/applicationset/webhook/webhook.go
index 28f00b1cf6..5c78001a1d 100644
--- a/applicationset/webhook/webhook.go
+++ b/applicationset/webhook/webhook.go
@@ -7,7 +7,6 @@ import (
"net/http"
"net/url"
"regexp"
- "slices"
"strconv"
"strings"
"sync"
@@ -16,11 +15,11 @@ import (
"k8s.io/client-go/util/retry"
"sigs.k8s.io/controller-runtime/pkg/client"
- "github.com/argoproj/argo-cd/v3/applicationset/generators"
- "github.com/argoproj/argo-cd/v3/common"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- argosettings "github.com/argoproj/argo-cd/v3/util/settings"
- "github.com/argoproj/argo-cd/v3/util/webhook"
+ "github.com/argoproj/argo-cd/v2/applicationset/generators"
+ "github.com/argoproj/argo-cd/v2/common"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+ argosettings "github.com/argoproj/argo-cd/v2/util/settings"
+ "github.com/argoproj/argo-cd/v2/util/webhook"
"github.com/go-playground/webhooks/v6/azuredevops"
"github.com/go-playground/webhooks/v6/github"
@@ -38,7 +37,7 @@ type WebhookHandler struct {
azuredevops *azuredevops.Webhook
client client.Client
generators map[string]generators.Generator
- queue chan any
+ queue chan interface{}
}
type gitGeneratorInfo struct {
@@ -73,19 +72,19 @@ func NewWebhookHandler(namespace string, webhookParallelism int, argocdSettingsM
// register the webhook secrets stored under "argocd-secret" for verifying incoming payloads
argocdSettings, err := argocdSettingsMgr.GetSettings()
if err != nil {
- return nil, fmt.Errorf("failed to get argocd settings: %w", err)
+ return nil, fmt.Errorf("Failed to get argocd settings: %w", err)
}
githubHandler, err := github.New(github.Options.Secret(argocdSettings.WebhookGitHubSecret))
if err != nil {
- return nil, fmt.Errorf("unable to init GitHub webhook: %w", err)
+ return nil, fmt.Errorf("Unable to init GitHub webhook: %w", err)
}
gitlabHandler, err := gitlab.New(gitlab.Options.Secret(argocdSettings.WebhookGitLabSecret))
if err != nil {
- return nil, fmt.Errorf("unable to init GitLab webhook: %w", err)
+ return nil, fmt.Errorf("Unable to init GitLab webhook: %w", err)
}
azuredevopsHandler, err := azuredevops.New(azuredevops.Options.BasicAuth(argocdSettings.WebhookAzureDevOpsUsername, argocdSettings.WebhookAzureDevOpsPassword))
if err != nil {
- return nil, fmt.Errorf("unable to init Azure DevOps webhook: %w", err)
+ return nil, fmt.Errorf("Unable to init Azure DevOps webhook: %w", err)
}
webhookHandler := &WebhookHandler{
@@ -95,7 +94,7 @@ func NewWebhookHandler(namespace string, webhookParallelism int, argocdSettingsM
azuredevops: azuredevopsHandler,
client: client,
generators: generators,
- queue: make(chan any, payloadQueueSize),
+ queue: make(chan interface{}, payloadQueueSize),
}
webhookHandler.startWorkerPool(webhookParallelism)
@@ -119,7 +118,7 @@ func (h *WebhookHandler) startWorkerPool(webhookParallelism int) {
}
}
-func (h *WebhookHandler) HandleEvent(payload any) {
+func (h *WebhookHandler) HandleEvent(payload interface{}) {
gitGenInfo := getGitGeneratorInfo(payload)
prGenInfo := getPRGeneratorInfo(payload)
if gitGenInfo == nil && prGenInfo == nil {
@@ -158,14 +157,14 @@ func (h *WebhookHandler) HandleEvent(payload any) {
}
func (h *WebhookHandler) Handler(w http.ResponseWriter, r *http.Request) {
- var payload any
+ var payload interface{}
var err error
switch {
case r.Header.Get("X-GitHub-Event") != "":
payload, err = h.github.Parse(r, github.PushEvent, github.PullRequestEvent, github.PingEvent)
case r.Header.Get("X-Gitlab-Event") != "":
- payload, err = h.gitlab.Parse(r, gitlab.PushEvents, gitlab.TagEvents, gitlab.MergeRequestEvents, gitlab.SystemHookEvents)
+ payload, err = h.gitlab.Parse(r, gitlab.PushEvents, gitlab.TagEvents, gitlab.MergeRequestEvents)
case r.Header.Get("X-Vss-Activityid") != "":
payload, err = h.azuredevops.Parse(r, azuredevops.GitPushEventType, azuredevops.GitPullRequestCreatedEventType, azuredevops.GitPullRequestUpdatedEventType, azuredevops.GitPullRequestMergedEventType)
default:
@@ -180,7 +179,7 @@ func (h *WebhookHandler) Handler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
status = http.StatusMethodNotAllowed
}
- http.Error(w, "Webhook processing failed: "+html.EscapeString(err.Error()), status)
+ http.Error(w, fmt.Sprintf("Webhook processing failed: %s", html.EscapeString(err.Error())), status)
return
}
@@ -192,7 +191,7 @@ func (h *WebhookHandler) Handler(w http.ResponseWriter, r *http.Request) {
}
}
-func getGitGeneratorInfo(payload any) *gitGeneratorInfo {
+func getGitGeneratorInfo(payload interface{}) *gitGeneratorInfo {
var (
webURL string
revision string
@@ -218,7 +217,13 @@ func getGitGeneratorInfo(payload any) *gitGeneratorInfo {
}
log.Infof("Received push event repo: %s, revision: %s, touchedHead: %v", webURL, revision, touchedHead)
- repoRegexp, err := webhook.GetWebURLRegex(webURL)
+ urlObj, err := url.Parse(webURL)
+ if err != nil {
+ log.Errorf("Failed to parse repoURL '%s'", webURL)
+ return nil
+ }
+ regexpStr := `(?i)(http://|https://|\w+@|ssh://(\w+@)?)` + urlObj.Hostname() + "(:[0-9]+|)[:/]" + urlObj.Path[1:] + "(\\.git)?$"
+ repoRegexp, err := regexp.Compile(regexpStr)
if err != nil {
log.Errorf("Failed to compile regexp for repoURL '%s'", webURL)
return nil
@@ -231,16 +236,22 @@ func getGitGeneratorInfo(payload any) *gitGeneratorInfo {
}
}
-func getPRGeneratorInfo(payload any) *prGeneratorInfo {
+func getPRGeneratorInfo(payload interface{}) *prGeneratorInfo {
var info prGeneratorInfo
switch payload := payload.(type) {
case github.PullRequestPayload:
- if !slices.Contains(githubAllowedPullRequestActions, payload.Action) {
+ if !isAllowedGithubPullRequestAction(payload.Action) {
return nil
}
apiURL := payload.Repository.URL
- apiRegexp, err := webhook.GetAPIURLRegex(apiURL)
+ urlObj, err := url.Parse(apiURL)
+ if err != nil {
+ log.Errorf("Failed to parse repoURL '%s'", apiURL)
+ return nil
+ }
+ regexpStr := `(?i)(http://|https://|\w+@|ssh://(\w+@)?)` + urlObj.Hostname() + "(:[0-9]+|)[:/]"
+ apiRegexp, err := regexp.Compile(regexpStr)
if err != nil {
log.Errorf("Failed to compile regexp for repoURL '%s'", apiURL)
return nil
@@ -251,7 +262,7 @@ func getPRGeneratorInfo(payload any) *prGeneratorInfo {
APIRegexp: apiRegexp,
}
case gitlab.MergeRequestEventPayload:
- if !slices.Contains(gitlabAllowedPullRequestActions, payload.ObjectAttributes.Action) {
+ if !isAllowedGitlabPullRequestAction(payload.ObjectAttributes.Action) {
return nil
}
@@ -267,7 +278,7 @@ func getPRGeneratorInfo(payload any) *prGeneratorInfo {
APIHostname: urlObj.Hostname(),
}
case azuredevops.GitPullRequestEvent:
- if !slices.Contains(azuredevopsAllowedPullRequestActions, string(payload.EventType)) {
+ if !isAllowedAzureDevOpsPullRequestAction(string(payload.EventType)) {
return nil
}
@@ -312,6 +323,33 @@ var azuredevopsAllowedPullRequestActions = []string{
"git.pullrequest.updated",
}
+func isAllowedGithubPullRequestAction(action string) bool {
+ for _, allow := range githubAllowedPullRequestActions {
+ if allow == action {
+ return true
+ }
+ }
+ return false
+}
+
+func isAllowedGitlabPullRequestAction(action string) bool {
+ for _, allow := range gitlabAllowedPullRequestActions {
+ if allow == action {
+ return true
+ }
+ }
+ return false
+}
+
+func isAllowedAzureDevOpsPullRequestAction(action string) bool {
+ for _, allow := range azuredevopsAllowedPullRequestActions {
+ if allow == action {
+ return true
+ }
+ }
+ return false
+}
+
func shouldRefreshGitGenerator(gen *v1alpha1.GitGenerator, info *gitGeneratorInfo) bool {
if gen == nil || info == nil {
return false
@@ -479,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]any{}
+ params := []map[string]interface{}{}
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 311c522ebe..33a8d134ea 100644
--- a/applicationset/webhook/webhook_test.go
+++ b/applicationset/webhook/webhook_test.go
@@ -2,6 +2,7 @@ package webhook
import (
"bytes"
+ "context"
"fmt"
"io"
"net/http"
@@ -23,26 +24,26 @@ import (
apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
- "github.com/argoproj/argo-cd/v3/applicationset/generators"
- "github.com/argoproj/argo-cd/v3/applicationset/services/scm_provider"
- "github.com/argoproj/argo-cd/v3/common"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- argosettings "github.com/argoproj/argo-cd/v3/util/settings"
+ "github.com/argoproj/argo-cd/v2/applicationset/generators"
+ "github.com/argoproj/argo-cd/v2/applicationset/services/scm_provider"
+ "github.com/argoproj/argo-cd/v2/common"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+ argosettings "github.com/argoproj/argo-cd/v2/util/settings"
)
type generatorMock struct {
mock.Mock
}
-func (g *generatorMock) GetTemplate(_ *v1alpha1.ApplicationSetGenerator) *v1alpha1.ApplicationSetTemplate {
+func (g *generatorMock) GetTemplate(appSetGenerator *v1alpha1.ApplicationSetGenerator) *v1alpha1.ApplicationSetTemplate {
return &v1alpha1.ApplicationSetTemplate{}
}
-func (g *generatorMock) GenerateParams(_ *v1alpha1.ApplicationSetGenerator, _ *v1alpha1.ApplicationSet, _ client.Client) ([]map[string]any, error) {
- return []map[string]any{}, nil
+func (g *generatorMock) GenerateParams(appSetGenerator *v1alpha1.ApplicationSetGenerator, _ *v1alpha1.ApplicationSet, client client.Client) ([]map[string]interface{}, error) {
+ return []map[string]interface{}{}, nil
}
-func (g *generatorMock) GetRequeueAfter(_ *v1alpha1.ApplicationSetGenerator) time.Duration {
+func (g *generatorMock) GetRequeueAfter(appSetGenerator *v1alpha1.ApplicationSetGenerator) time.Duration {
d, _ := time.ParseDuration("10s")
return d
}
@@ -62,7 +63,7 @@ func TestWebhookHandler(t *testing.T) {
headerKey: "X-GitHub-Event",
headerValue: "push",
payloadFile: "github-commit-event.json",
- effectedAppSets: []string{"git-github", "git-github-ssh", "git-github-alt-ssh", "matrix-git-github", "merge-git-github", "matrix-scm-git-github", "matrix-nested-git-github", "merge-nested-git-github", "plugin", "matrix-pull-request-github-plugin"},
+ effectedAppSets: []string{"git-github", "matrix-git-github", "merge-git-github", "matrix-scm-git-github", "matrix-nested-git-github", "merge-nested-git-github", "plugin", "matrix-pull-request-github-plugin"},
expectedStatusCode: http.StatusOK,
expectedRefresh: true,
},
@@ -80,7 +81,7 @@ func TestWebhookHandler(t *testing.T) {
headerKey: "X-GitHub-Event",
headerValue: "push",
payloadFile: "github-commit-branch-event.json",
- effectedAppSets: []string{"git-github", "git-github-ssh", "git-github-alt-ssh", "plugin", "matrix-pull-request-github-plugin"},
+ effectedAppSets: []string{"git-github", "plugin", "matrix-pull-request-github-plugin"},
expectedStatusCode: http.StatusOK,
expectedRefresh: true,
},
@@ -89,7 +90,7 @@ func TestWebhookHandler(t *testing.T) {
headerKey: "X-GitHub-Event",
headerValue: "ping",
payloadFile: "github-ping-event.json",
- effectedAppSets: []string{"git-github", "git-github-ssh", "git-github-alt-ssh", "plugin"},
+ effectedAppSets: []string{"git-github", "plugin"},
expectedStatusCode: http.StatusOK,
expectedRefresh: false,
},
@@ -98,16 +99,7 @@ func TestWebhookHandler(t *testing.T) {
headerKey: "X-Gitlab-Event",
headerValue: "Push Hook",
payloadFile: "gitlab-event.json",
- effectedAppSets: []string{"git-gitlab", "git-gitlab-ssh", "git-gitlab-alt-ssh", "plugin", "matrix-pull-request-github-plugin"},
- expectedStatusCode: http.StatusOK,
- expectedRefresh: true,
- },
- {
- desc: "WebHook from a System Hook via Commit",
- headerKey: "X-Gitlab-Event",
- headerValue: "System Hook",
- payloadFile: "gitlab-event.json",
- effectedAppSets: []string{"git-gitlab", "git-gitlab-ssh", "git-gitlab-alt-ssh", "plugin", "matrix-pull-request-github-plugin"},
+ effectedAppSets: []string{"git-gitlab", "plugin", "matrix-pull-request-github-plugin"},
expectedStatusCode: http.StatusOK,
expectedRefresh: true,
},
@@ -116,7 +108,7 @@ func TestWebhookHandler(t *testing.T) {
headerKey: "X-Random-Event",
headerValue: "Push Hook",
payloadFile: "gitlab-event.json",
- effectedAppSets: []string{"git-gitlab", "git-gitlab-ssh", "git-gitlab-alt-ssh", "plugin"},
+ effectedAppSets: []string{"git-gitlab", "plugin"},
expectedStatusCode: http.StatusBadRequest,
expectedRefresh: false,
},
@@ -125,7 +117,7 @@ func TestWebhookHandler(t *testing.T) {
headerKey: "X-Random-Event",
headerValue: "Push Hook",
payloadFile: "invalid-event.json",
- effectedAppSets: []string{"git-gitlab", "git-gitlab-ssh", "git-gitlab-alt-ssh", "plugin"},
+ effectedAppSets: []string{"git-gitlab", "plugin"},
expectedStatusCode: http.StatusBadRequest,
expectedRefresh: false,
},
@@ -208,11 +200,7 @@ func TestWebhookHandler(t *testing.T) {
fc := fake.NewClientBuilder().WithScheme(scheme).WithObjects(
fakeAppWithGitGenerator("git-github", namespace, "https://github.com/org/repo"),
fakeAppWithGitGenerator("git-github-copy", namespace, "https://github.com/org/repo-copy"),
- fakeAppWithGitGenerator("git-github-ssh", namespace, "ssh://git@github.com/org/repo"),
- fakeAppWithGitGenerator("git-github-alt-ssh", namespace, "ssh://git@ssh.github.com:443/org/repo"),
- fakeAppWithGitGenerator("git-gitlab", namespace, "https://gitlab.com/group/name"),
- fakeAppWithGitGenerator("git-gitlab-ssh", namespace, "ssh://git@gitlab.com/group/name"),
- fakeAppWithGitGenerator("git-gitlab-alt-ssh", namespace, "ssh://git@altssh.gitlab.com:443/group/name"),
+ fakeAppWithGitGenerator("git-gitlab", namespace, "https://gitlab/group/name"),
fakeAppWithGitGenerator("git-azure-devops", namespace, "https://dev.azure.com/fabrikam-fiber-inc/DefaultCollection/_git/Fabrikam-Fiber-Git"),
fakeAppWithGitGeneratorWithRevision("github-shorthand", namespace, "https://github.com/org/repo", "env/dev"),
fakeAppWithGithubPullRequestGenerator("pull-request-github", namespace, "CodErTOcat", "Hello-World"),
@@ -229,7 +217,7 @@ func TestWebhookHandler(t *testing.T) {
fakeAppWithMergeAndPullRequestGenerator("merge-pull-request-github", namespace, "Codertocat", "Hello-World"),
fakeAppWithMergeAndNestedGitGenerator("merge-nested-git-github", namespace, "https://github.com/org/repo"),
).Build()
- set := argosettings.NewSettingsManager(t.Context(), fakeClient, namespace)
+ set := argosettings.NewSettingsManager(context.TODO(), fakeClient, namespace)
h, err := NewWebhookHandler(namespace, webhookParallelism, set, fc, mockGenerators())
require.NoError(t, err)
@@ -246,7 +234,7 @@ func TestWebhookHandler(t *testing.T) {
assert.Equal(t, test.expectedStatusCode, w.Code)
list := &v1alpha1.ApplicationSetList{}
- err = fc.List(t.Context(), list)
+ err = fc.List(context.TODO(), list)
require.NoError(t, err)
effectedAppSetsAsExpected := make(map[string]bool)
for _, appSetName := range test.effectedAppSets {
diff --git a/assets/swagger.json b/assets/swagger.json
index 5f4f2fbe33..9436a6a6f4 100644
--- a/assets/swagger.json
+++ b/assets/swagger.json
@@ -920,11 +920,6 @@
"type": "string",
"name": "project",
"in": "query"
- },
- {
- "type": "boolean",
- "name": "matchCase",
- "in": "query"
}
],
"responses": {
@@ -1158,11 +1153,6 @@
"type": "string",
"name": "project",
"in": "query"
- },
- {
- "type": "boolean",
- "name": "matchCase",
- "in": "query"
}
],
"responses": {
@@ -1490,8 +1480,43 @@
"in": "body",
"required": true,
"schema": {
- "$ref": "#/definitions/applicationResourceActionRunRequest"
+ "type": "string"
}
+ },
+ {
+ "type": "string",
+ "name": "namespace",
+ "in": "query"
+ },
+ {
+ "type": "string",
+ "name": "resourceName",
+ "in": "query"
+ },
+ {
+ "type": "string",
+ "name": "version",
+ "in": "query"
+ },
+ {
+ "type": "string",
+ "name": "group",
+ "in": "query"
+ },
+ {
+ "type": "string",
+ "name": "kind",
+ "in": "query"
+ },
+ {
+ "type": "string",
+ "name": "appNamespace",
+ "in": "query"
+ },
+ {
+ "type": "string",
+ "name": "project",
+ "in": "query"
}
],
"responses": {
@@ -3746,18 +3771,6 @@
"description": "Whether to force HTTP basic auth.",
"name": "forceHttpBasicAuth",
"in": "query"
- },
- {
- "type": "boolean",
- "description": "Whether to use azure workload identity for authentication.",
- "name": "useAzureWorkloadIdentity",
- "in": "query"
- },
- {
- "type": "string",
- "description": "BearerToken contains the bearer token used for Git auth at the repo server.",
- "name": "bearerToken",
- "in": "query"
}
],
"responses": {
@@ -4584,18 +4597,6 @@
"description": "Whether to force HTTP basic auth.",
"name": "forceHttpBasicAuth",
"in": "query"
- },
- {
- "type": "boolean",
- "description": "Whether to use azure workload identity for authentication.",
- "name": "useAzureWorkloadIdentity",
- "in": "query"
- },
- {
- "type": "string",
- "description": "BearerToken contains the bearer token used for Git auth at the repo server.",
- "name": "bearerToken",
- "in": "query"
}
],
"responses": {
@@ -4997,55 +4998,6 @@
"applicationOperationTerminateResponse": {
"type": "object"
},
- "applicationResourceActionParameters": {
- "type": "object",
- "properties": {
- "name": {
- "type": "string"
- },
- "value": {
- "type": "string"
- }
- }
- },
- "applicationResourceActionRunRequest": {
- "type": "object",
- "properties": {
- "action": {
- "type": "string"
- },
- "appNamespace": {
- "type": "string"
- },
- "group": {
- "type": "string"
- },
- "kind": {
- "type": "string"
- },
- "name": {
- "type": "string"
- },
- "namespace": {
- "type": "string"
- },
- "project": {
- "type": "string"
- },
- "resourceActionParameters": {
- "type": "array",
- "items": {
- "$ref": "#/definitions/applicationResourceActionParameters"
- }
- },
- "resourceName": {
- "type": "string"
- },
- "version": {
- "type": "string"
- }
- }
- },
"applicationResourceActionsListResponse": {
"type": "object",
"properties": {
@@ -5115,51 +5067,41 @@
}
},
"applicationv1alpha1ResourceStatus": {
- "description": "ResourceStatus holds the current synchronization and health status of a Kubernetes resource.",
"type": "object",
+ "title": "ResourceStatus holds the current sync and health status of a resource\nTODO: describe members of this type",
"properties": {
"group": {
- "description": "Group represents the API group of the resource (e.g., \"apps\" for Deployments).",
"type": "string"
},
"health": {
"$ref": "#/definitions/v1alpha1HealthStatus"
},
"hook": {
- "description": "Hook is true if the resource is used as a lifecycle hook in an Argo CD application.",
"type": "boolean"
},
"kind": {
- "description": "Kind specifies the type of the resource (e.g., \"Deployment\", \"Service\").",
"type": "string"
},
"name": {
- "description": "Name is the unique name of the resource within the namespace.",
"type": "string"
},
"namespace": {
- "description": "Namespace defines the Kubernetes namespace where the resource is located.",
"type": "string"
},
"requiresDeletionConfirmation": {
- "description": "RequiresDeletionConfirmation is true if the resource requires explicit user confirmation before deletion.",
"type": "boolean"
},
"requiresPruning": {
- "description": "RequiresPruning is true if the resource needs to be pruned (deleted) as part of synchronization.",
"type": "boolean"
},
"status": {
- "description": "Status represents the synchronization state of the resource (e.g., Synced, OutOfSync).",
"type": "string"
},
"syncWave": {
- "description": "SyncWave determines the order in which resources are applied during a sync operation.\nLower values are applied first.",
"type": "integer",
"format": "int64"
},
"version": {
- "description": "Version indicates the API version of the resource (e.g., \"v1\", \"v1beta1\").",
"type": "string"
}
}
@@ -6453,7 +6395,6 @@
},
"v1PortStatus": {
"type": "object",
- "title": "PortStatus represents the error condition of a service port",
"properties": {
"error": {
"type": "string",
@@ -6493,24 +6434,6 @@
}
}
},
- "v1alpha1AppHealthStatus": {
- "type": "object",
- "title": "AppHealthStatus contains information about the currently observed health state of an application",
- "properties": {
- "lastTransitionTime": {
- "$ref": "#/definitions/v1Time"
- },
- "message": {
- "description": "Deprecated: this field is not used and will be removed in a future release.",
- "type": "string",
- "title": "Message is a human-readable informational message describing the health status"
- },
- "status": {
- "type": "string",
- "title": "Status holds the status code of the application"
- }
- }
- },
"v1alpha1AppProject": {
"type": "object",
"title": "AppProject provides a logical grouping of applications, providing controls for:\n* where the apps may deploy to (cluster whitelist)\n* what may be deployed (repository whitelist, resource whitelist/blacklist)\n* who can access these applications (roles, OIDC group claims bindings)\n* and what they can do (RBAC policies)\n* automation access to these roles (JWT tokens)\n+genclient\n+genclient:noStatus\n+k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object\n+kubebuilder:resource:path=appprojects,shortName=appproj;appprojs",
@@ -6561,7 +6484,7 @@
},
"description": {
"type": "string",
- "title": "Description contains optional project description\n+kubebuilder:validation:MaxLength=255"
+ "title": "Description contains optional project description"
},
"destinationServiceAccounts": {
"description": "DestinationServiceAccounts holds information about the service accounts to be impersonated for the application sync operation for each destination.",
@@ -6981,8 +6904,8 @@
"type": "object",
"properties": {
"applyNestedSelectors": {
- "description": "ApplyNestedSelectors enables selectors defined within the generators of two level-nested matrix or merge generators\nDeprecated: This field is ignored, and the behavior is always enabled. The field will be removed in a future\nversion of the ApplicationSet CRD.",
- "type": "boolean"
+ "type": "boolean",
+ "title": "ApplyNestedSelectors enables selectors defined within the generators of two level-nested matrix or merge generators"
},
"generators": {
"type": "array",
@@ -7340,10 +7263,6 @@
"type": "boolean",
"title": "ForceCommonLabels specifies whether to force applying common labels to resources for Kustomize apps"
},
- "ignoreMissingComponents": {
- "type": "boolean",
- "title": "IgnoreMissingComponents prevents kustomize from failing when components do not exist locally by not appending them to kustomization file"
- },
"images": {
"type": "array",
"title": "Images is a list of Kustomize image override specifications",
@@ -7355,10 +7274,6 @@
"description": "KubeVersion specifies the Kubernetes API version to pass to Helm when templating manifests. By default, Argo CD\nuses the Kubernetes version of the target cluster.",
"type": "string"
},
- "labelIncludeTemplates": {
- "type": "boolean",
- "title": "LabelIncludeTemplates specifies whether to apply common labels to resource templates or not"
- },
"labelWithoutSelector": {
"type": "boolean",
"title": "LabelWithoutSelector specifies whether to apply common labels to resource selectors or not"
@@ -7507,7 +7422,7 @@
"title": "ControllerNamespace indicates the namespace in which the application controller is located"
},
"health": {
- "$ref": "#/definitions/v1alpha1AppHealthStatus"
+ "$ref": "#/definitions/v1alpha1HealthStatus"
},
"history": {
"type": "array",
@@ -7579,34 +7494,34 @@
}
},
"v1alpha1ApplicationTree": {
- "description": "ApplicationTree represents the hierarchical structure of resources associated with an Argo CD application.",
"type": "object",
+ "title": "ApplicationTree holds nodes which belongs to the application\nTODO: describe purpose of this type",
"properties": {
"hosts": {
- "description": "Hosts provides a list of Kubernetes nodes that are running pods related to the application.",
"type": "array",
+ "title": "Hosts holds list of Kubernetes nodes that run application related pods",
"items": {
"$ref": "#/definitions/v1alpha1HostInfo"
}
},
"nodes": {
- "description": "Nodes contains a list of resources that are either directly managed by the application\nor are children of directly managed resources.",
+ "description": "Nodes contains list of nodes which either directly managed by the application and children of directly managed nodes.",
"type": "array",
"items": {
"$ref": "#/definitions/v1alpha1ResourceNode"
}
},
"orphanedNodes": {
- "description": "OrphanedNodes contains resources that exist in the same namespace as the application\nbut are not managed by it. This list is populated only if orphaned resource tracking\nis enabled in the application's project settings.",
+ "description": "OrphanedNodes contains if or orphaned nodes: nodes which are not managed by the app but in the same namespace. List is populated only if orphaned resources enabled in app project.",
"type": "array",
"items": {
"$ref": "#/definitions/v1alpha1ResourceNode"
}
},
"shardsCount": {
- "description": "ShardsCount represents the total number of shards the application tree is split into.\nThis is used to distribute resource processing across multiple shards.",
"type": "integer",
- "format": "int64"
+ "format": "int64",
+ "title": "ShardsCount contains total number of shards the application tree is split into"
}
}
},
@@ -8060,9 +7975,6 @@
"v1alpha1GitFileGeneratorItem": {
"type": "object",
"properties": {
- "exclude": {
- "type": "boolean"
- },
"path": {
"type": "string"
}
@@ -8155,7 +8067,7 @@
},
"v1alpha1HealthStatus": {
"type": "object",
- "title": "HealthStatus contains information about the currently observed health state of a resource",
+ "title": "HealthStatus contains information about the currently observed health state of an application or resource",
"properties": {
"lastTransitionTime": {
"$ref": "#/definitions/v1Time"
@@ -8166,7 +8078,7 @@
},
"status": {
"type": "string",
- "title": "Status holds the status code of the resource"
+ "title": "Status holds the status code of the application or resource"
}
}
},
@@ -8203,15 +8115,13 @@
}
},
"v1alpha1HostInfo": {
- "description": "HostInfo holds metadata and resource usage metrics for a specific host in the cluster.",
"type": "object",
+ "title": "HostInfo holds host name and resources metrics\nTODO: describe purpose of this type\nTODO: describe members of this type",
"properties": {
"name": {
- "description": "Name is the hostname or node name in the Kubernetes cluster.",
"type": "string"
},
"resourcesInfo": {
- "description": "ResourcesInfo provides a list of resource usage details for different resource types on this host.",
"type": "array",
"items": {
"$ref": "#/definitions/v1alpha1HostResourceInfo"
@@ -8223,26 +8133,22 @@
}
},
"v1alpha1HostResourceInfo": {
- "description": "HostResourceInfo represents resource usage details for a specific resource type on a host.",
"type": "object",
+ "title": "TODO: describe this type",
"properties": {
"capacity": {
- "description": "Capacity represents the total available capacity of this resource on the host.",
"type": "integer",
"format": "int64"
},
"requestedByApp": {
- "description": "RequestedByApp indicates the total amount of this resource requested by the application running on the host.",
"type": "integer",
"format": "int64"
},
"requestedByNeighbors": {
- "description": "RequestedByNeighbors indicates the total amount of this resource requested by other workloads on the same host.",
"type": "integer",
"format": "int64"
},
"resourceName": {
- "description": "ResourceName specifies the type of resource (e.g., CPU, memory, storage).",
"type": "string"
}
}
@@ -8358,15 +8264,13 @@
}
},
"v1alpha1KnownTypeField": {
- "description": "KnownTypeField contains a mapping between a Custom Resource Definition (CRD) field\nand a well-known Kubernetes type. This mapping is primarily used for unit conversions\nin resources where the type is not explicitly defined (e.g., converting \"0.1\" to \"100m\" for CPU requests).",
"type": "object",
+ "title": "KnownTypeField contains mapping between CRD field and known Kubernetes type.\nThis is mainly used for unit conversion in unknown resources (e.g. 0.1 == 100mi)\nTODO: Describe the members of this type",
"properties": {
"field": {
- "type": "string",
- "title": "Field represents the JSON path to the specific field in the CRD that requires type conversion.\nExample: \"spec.resources.requests.cpu\""
+ "type": "string"
},
"type": {
- "description": "Type specifies the expected Kubernetes type for the field, such as \"cpu\" or \"memory\".\nThis helps in converting values between different formats (e.g., \"0.1\" to \"100m\" for CPU).",
"type": "string"
}
}
@@ -8776,13 +8680,6 @@
},
"template": {
"$ref": "#/definitions/v1alpha1ApplicationSetTemplate"
- },
- "values": {
- "type": "object",
- "title": "Values contains key/value pairs which are passed directly as parameters to the template",
- "additionalProperties": {
- "type": "string"
- }
}
}
},
@@ -8912,8 +8809,8 @@
"type": "string"
},
"pullRequestState": {
- "description": "PullRequestState is an additional MRs filter to get only those with a certain state. Default: \"\" (all states).\nValid values: opened, closed, merged, locked\".",
- "type": "string"
+ "type": "string",
+ "title": "PullRequestState is an additional MRs filter to get only those with a certain state. Default: \"\" (all states)"
},
"tokenRef": {
"$ref": "#/definitions/v1alpha1SecretRef"
@@ -8932,13 +8829,6 @@
"description": "Allow insecure tls, for self-signed certificates; default: false.",
"type": "boolean"
},
- "labels": {
- "type": "array",
- "title": "Labels is used to filter the PRs that you want to target",
- "items": {
- "type": "string"
- }
- },
"owner": {
"description": "Gitea org or user to scan. Required.",
"type": "string"
@@ -8988,10 +8878,6 @@
"type": "object",
"title": "RepoCreds holds the definition for repository credentials",
"properties": {
- "bearerToken": {
- "type": "string",
- "title": "BearerToken contains the bearer token used for Git BitBucket Data Center auth at the repo server"
- },
"enableOCI": {
"type": "boolean",
"title": "EnableOCI specifies whether helm-oci support should be enabled for this repo"
@@ -9054,10 +8940,6 @@
"type": "string",
"title": "URL is the URL to which these credentials match"
},
- "useAzureWorkloadIdentity": {
- "type": "boolean",
- "title": "UseAzureWorkloadIdentity specifies whether to use Azure Workload Identity for authentication"
- },
"username": {
"type": "string",
"title": "Username for authenticating at the repo server"
@@ -9083,10 +8965,6 @@
"type": "object",
"title": "Repository is a repository holding application configurations",
"properties": {
- "bearerToken": {
- "type": "string",
- "title": "BearerToken contains the bearer token used for Git BitBucket Data Center auth at the repo server"
- },
"connectionState": {
"$ref": "#/definitions/v1alpha1ConnectionState"
},
@@ -9176,10 +9054,6 @@
"description": "Type specifies the type of the repo. Can be either \"git\" or \"helm. \"git\" is assumed if empty or absent.",
"type": "string"
},
- "useAzureWorkloadIdentity": {
- "type": "boolean",
- "title": "UseAzureWorkloadIdentity specifies whether to use Azure Workload Identity for authentication"
- },
"username": {
"type": "string",
"title": "Username contains the user name used for authenticating at the remote repository"
@@ -9245,27 +9119,22 @@
}
},
"v1alpha1ResourceAction": {
- "description": "ResourceAction represents an individual action that can be performed on a resource.\nIt includes parameters, an optional disabled flag, an icon for display, and a name for the action.",
"type": "object",
+ "title": "TODO: describe this type\nTODO: describe members of this type",
"properties": {
"disabled": {
- "description": "Disabled indicates whether the action is disabled.",
"type": "boolean"
},
"displayName": {
- "description": "DisplayName provides a user-friendly name for the action.",
"type": "string"
},
"iconClass": {
- "description": "IconClass specifies the CSS class for the action's icon.",
"type": "string"
},
"name": {
- "description": "Name is the name or identifier for the action.",
"type": "string"
},
"params": {
- "description": "Params contains the parameters required to execute the action.",
"type": "array",
"items": {
"$ref": "#/definitions/v1alpha1ResourceActionParam"
@@ -9274,78 +9143,67 @@
}
},
"v1alpha1ResourceActionParam": {
- "description": "ResourceActionParam represents a parameter for a resource action.\nIt includes a name, value, type, and an optional default value for the parameter.",
"type": "object",
+ "title": "TODO: describe this type\nTODO: describe members of this type",
"properties": {
"default": {
- "description": "Default is the default value of the parameter, if any.",
"type": "string"
},
"name": {
- "description": "Name is the name of the parameter.",
"type": "string"
},
"type": {
- "description": "Type is the type of the parameter (e.g., string, integer).",
"type": "string"
},
"value": {
- "description": "Value is the value of the parameter.",
"type": "string"
}
}
},
"v1alpha1ResourceDiff": {
- "description": "ResourceDiff holds the diff between a live and target resource object in Argo CD.\nIt is used to compare the desired state (from Git/Helm) with the actual state in the cluster.",
"type": "object",
+ "title": "ResourceDiff holds the diff of a live and target resource object\nTODO: describe members of this type",
"properties": {
"diff": {
- "description": "Diff contains the JSON patch representing the difference between the live and target resource.\nDeprecated: Use NormalizedLiveState and PredictedLiveState instead to compute differences.",
- "type": "string"
+ "type": "string",
+ "title": "Diff contains the JSON patch between target and live resource\nDeprecated: use NormalizedLiveState and PredictedLiveState to render the difference"
},
"group": {
- "description": "Group represents the API group of the resource (e.g., \"apps\" for Deployments).",
"type": "string"
},
"hook": {
- "description": "Hook indicates whether this resource is a hook resource (e.g., pre-sync or post-sync hooks).",
"type": "boolean"
},
"kind": {
- "description": "Kind represents the Kubernetes resource kind (e.g., \"Deployment\", \"Service\").",
"type": "string"
},
"liveState": {
- "description": "LiveState contains the JSON-serialized resource manifest of the resource currently running in the cluster.",
- "type": "string"
+ "type": "string",
+ "title": "TargetState contains the JSON live resource manifest"
},
"modified": {
- "description": "Modified indicates whether the live resource has changes compared to the target resource.",
"type": "boolean"
},
"name": {
- "description": "Name is the name of the resource.",
"type": "string"
},
"namespace": {
- "description": "Namespace specifies the namespace where the resource exists.",
"type": "string"
},
"normalizedLiveState": {
- "description": "NormalizedLiveState contains the JSON-serialized live resource state after applying normalizations.\nNormalizations may include ignoring irrelevant fields like timestamps or defaults applied by Kubernetes.",
- "type": "string"
+ "type": "string",
+ "title": "NormalizedLiveState contains JSON serialized live resource state with applied normalizations"
},
"predictedLiveState": {
- "description": "PredictedLiveState contains the JSON-serialized resource state that Argo CD predicts based on the\ncombination of the normalized live state and the desired target state.",
- "type": "string"
+ "type": "string",
+ "title": "PredictedLiveState contains JSON serialized resource state that is calculated based on normalized and target resource state"
},
"resourceVersion": {
- "description": "ResourceVersion is the Kubernetes resource version, which helps in tracking changes.",
"type": "string"
},
"targetState": {
- "description": "TargetState contains the JSON-serialized resource manifest as defined in the Git/Helm repository.",
- "type": "string"
+ "type": "string",
+ "title": "TargetState contains the JSON serialized resource manifest defined in the Git/Helm"
}
}
},
@@ -9387,39 +9245,35 @@
}
},
"v1alpha1ResourceNetworkingInfo": {
- "description": "ResourceNetworkingInfo holds networking-related information for a resource.",
"type": "object",
+ "title": "ResourceNetworkingInfo holds networking resource related information\nTODO: describe members of this type",
"properties": {
"externalURLs": {
- "description": "ExternalURLs holds a list of URLs that should be accessible externally.\nThis field is typically populated for Ingress resources based on their hostname rules.",
+ "description": "ExternalURLs holds list of URLs which should be available externally. List is populated for ingress resources using rules hostnames.",
"type": "array",
"items": {
"type": "string"
}
},
"ingress": {
- "description": "Ingress provides information about external access points (e.g., load balancer ingress) for this resource.",
"type": "array",
"items": {
"$ref": "#/definitions/v1LoadBalancerIngress"
}
},
"labels": {
- "description": "Labels holds the labels associated with this networking resource.",
"type": "object",
"additionalProperties": {
"type": "string"
}
},
"targetLabels": {
- "description": "TargetLabels represents labels associated with the target resources that this resource communicates with.",
"type": "object",
"additionalProperties": {
"type": "string"
}
},
"targetRefs": {
- "description": "TargetRefs contains references to other resources that this resource interacts with, such as Services or Pods.",
"type": "array",
"items": {
"$ref": "#/definitions/v1alpha1ResourceRef"
@@ -9428,8 +9282,8 @@
}
},
"v1alpha1ResourceNode": {
- "description": "ResourceNode contains information about a live Kubernetes resource and its relationships with other resources.",
"type": "object",
+ "title": "ResourceNode contains information about live resource and its children\nTODO: describe members of this type",
"properties": {
"createdAt": {
"$ref": "#/definitions/v1Time"
@@ -9438,14 +9292,12 @@
"$ref": "#/definitions/v1alpha1HealthStatus"
},
"images": {
- "description": "Images lists container images associated with the resource.\nThis is primarily useful for pods and other workload resources.",
"type": "array",
"items": {
"type": "string"
}
},
"info": {
- "description": "Info provides additional metadata or annotations about the resource.",
"type": "array",
"items": {
"$ref": "#/definitions/v1alpha1InfoItem"
@@ -9455,14 +9307,12 @@
"$ref": "#/definitions/v1alpha1ResourceNetworkingInfo"
},
"parentRefs": {
- "description": "ParentRefs lists the parent resources that reference this resource.\nThis helps in understanding ownership and hierarchical relationships.",
"type": "array",
"items": {
"$ref": "#/definitions/v1alpha1ResourceRef"
}
},
"resourceVersion": {
- "description": "ResourceVersion indicates the version of the resource, used to track changes.",
"type": "string"
}
},
@@ -9474,14 +9324,12 @@
},
"v1alpha1ResourceOverride": {
"type": "object",
- "title": "ResourceOverride holds configuration to customize resource diffing and health assessment",
+ "title": "ResourceOverride holds configuration to customize resource diffing and health assessment\nTODO: describe the members of this type",
"properties": {
"actions": {
- "description": "Actions defines the set of actions that can be performed on the resource, as a Lua script.",
"type": "string"
},
"healthLua": {
- "description": "HealthLua contains a Lua script that defines custom health checks for the resource.",
"type": "string"
},
"ignoreDifferences": {
@@ -9491,14 +9339,12 @@
"$ref": "#/definitions/v1alpha1OverrideIgnoreDiff"
},
"knownTypeFields": {
- "description": "KnownTypeFields lists fields for which unit conversions should be applied.",
"type": "array",
"items": {
"$ref": "#/definitions/v1alpha1KnownTypeField"
}
},
"useOpenLibs": {
- "description": "UseOpenLibs indicates whether to use open-source libraries for the resource.",
"type": "boolean"
}
}
@@ -10148,10 +9994,6 @@
"type": "boolean",
"title": "AllowEmpty allows apps have zero live resources (default: false)"
},
- "enable": {
- "type": "boolean",
- "title": "Enable allows apps to explicitly control automated sync"
- },
"prune": {
"type": "boolean",
"title": "Prune specifies whether to delete resources from the cluster that are not found in the sources anymore as part of automated sync (default: false)"
@@ -10235,10 +10077,6 @@
"type": "object",
"title": "SyncWindow contains the kind, time, duration and attributes that are used to assign the syncWindows to apps",
"properties": {
- "andOperator": {
- "type": "boolean",
- "title": "UseAndOperator use AND operator for matching applications, namespaces and clusters instead of the default OR operator"
- },
"applications": {
"type": "array",
"title": "Applications contains a list of applications that the window will apply to",
@@ -10253,10 +10091,6 @@
"type": "string"
}
},
- "description": {
- "type": "string",
- "title": "Description of the sync that will be applied to the schedule, can be used to add any information such as a ticket number for example"
- },
"duration": {
"type": "string",
"title": "Duration is the amount of time the sync window will be open"
diff --git a/cmd/argocd-application-controller/commands/argocd_application_controller.go b/cmd/argocd-application-controller/commands/argocd_application_controller.go
index d9f3e2d9cb..3d140b97dc 100644
--- a/cmd/argocd-application-controller/commands/argocd_application_controller.go
+++ b/cmd/argocd-application-controller/commands/argocd_application_controller.go
@@ -10,7 +10,7 @@ import (
"syscall"
"time"
- "github.com/argoproj/pkg/v2/stats"
+ "github.com/argoproj/pkg/stats"
"github.com/redis/go-redis/v9"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
@@ -18,39 +18,35 @@ import (
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
- cmdutil "github.com/argoproj/argo-cd/v3/cmd/util"
- commitclient "github.com/argoproj/argo-cd/v3/commitserver/apiclient"
- "github.com/argoproj/argo-cd/v3/common"
- "github.com/argoproj/argo-cd/v3/controller"
- "github.com/argoproj/argo-cd/v3/controller/sharding"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- appclientset "github.com/argoproj/argo-cd/v3/pkg/client/clientset/versioned"
- "github.com/argoproj/argo-cd/v3/pkg/ratelimiter"
- "github.com/argoproj/argo-cd/v3/reposerver/apiclient"
- "github.com/argoproj/argo-cd/v3/util/argo"
- "github.com/argoproj/argo-cd/v3/util/argo/normalizers"
- cacheutil "github.com/argoproj/argo-cd/v3/util/cache"
- appstatecache "github.com/argoproj/argo-cd/v3/util/cache/appstate"
- "github.com/argoproj/argo-cd/v3/util/cli"
- "github.com/argoproj/argo-cd/v3/util/env"
- "github.com/argoproj/argo-cd/v3/util/errors"
- kubeutil "github.com/argoproj/argo-cd/v3/util/kube"
- "github.com/argoproj/argo-cd/v3/util/settings"
- "github.com/argoproj/argo-cd/v3/util/tls"
- "github.com/argoproj/argo-cd/v3/util/trace"
+ cmdutil "github.com/argoproj/argo-cd/v2/cmd/util"
+ commitclient "github.com/argoproj/argo-cd/v2/commitserver/apiclient"
+ "github.com/argoproj/argo-cd/v2/common"
+ "github.com/argoproj/argo-cd/v2/controller"
+ "github.com/argoproj/argo-cd/v2/controller/sharding"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+ appclientset "github.com/argoproj/argo-cd/v2/pkg/client/clientset/versioned"
+ "github.com/argoproj/argo-cd/v2/pkg/ratelimiter"
+ "github.com/argoproj/argo-cd/v2/reposerver/apiclient"
+ "github.com/argoproj/argo-cd/v2/util/argo"
+ "github.com/argoproj/argo-cd/v2/util/argo/normalizers"
+ 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/cli"
+ "github.com/argoproj/argo-cd/v2/util/env"
+ "github.com/argoproj/argo-cd/v2/util/errors"
+ kubeutil "github.com/argoproj/argo-cd/v2/util/kube"
+ "github.com/argoproj/argo-cd/v2/util/settings"
+ "github.com/argoproj/argo-cd/v2/util/tls"
+ "github.com/argoproj/argo-cd/v2/util/trace"
)
const (
// CLIName is the name of the CLI
cliName = common.ApplicationController
// Default time in seconds for application resync period
- defaultAppResyncPeriod = 120
- // Default time in seconds for application resync period jitter
- defaultAppResyncPeriodJitter = 60
+ defaultAppResyncPeriod = 180
// Default time in seconds for application hard resync period
defaultAppHardResyncPeriod = 0
- // Default time in seconds for ignoring consecutive errors when comminicating with repo-server
- defaultRepoErrorGracePeriod = defaultAppResyncPeriod + defaultAppResyncPeriodJitter
)
func NewCommand() *cobra.Command {
@@ -77,7 +73,6 @@ func NewCommand() *cobra.Command {
metricsCacheExpiration time.Duration
metricsAplicationLabels []string
metricsAplicationConditions []string
- metricsClusterLabels []string
kubectlParallelismLimit int64
cacheSource func() (*appstatecache.Cache, error)
redisClient *redis.Client
@@ -103,7 +98,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, _ []string) error {
+ RunE: func(c *cobra.Command, args []string) error {
ctx, cancel := context.WithCancel(c.Context())
defer cancel()
@@ -155,8 +150,8 @@ func NewCommand() *cobra.Command {
// repository server, if strict TLS validation was requested.
if !repoServerPlaintext && repoServerStrictTLS {
pool, err := tls.LoadX509CertPool(
- env.StringFromEnv(common.EnvAppConfigPath, common.DefaultAppConfigPath)+"/controller/tls/tls.crt",
- env.StringFromEnv(common.EnvAppConfigPath, common.DefaultAppConfigPath)+"/controller/tls/ca.crt",
+ fmt.Sprintf("%s/controller/tls/tls.crt", env.StringFromEnv(common.EnvAppConfigPath, common.DefaultAppConfigPath)),
+ fmt.Sprintf("%s/controller/tls/ca.crt", env.StringFromEnv(common.EnvAppConfigPath, common.DefaultAppConfigPath)),
)
if err != nil {
log.Fatalf("%v", err)
@@ -209,7 +204,6 @@ func NewCommand() *cobra.Command {
metricsCacheExpiration,
metricsAplicationLabels,
metricsAplicationConditions,
- metricsClusterLabels,
kubectlParallelismLimit,
persistResourceHealth,
clusterSharding,
@@ -258,14 +252,14 @@ func NewCommand() *cobra.Command {
clientConfig = cli.AddKubectlFlagsToCmd(&command)
command.Flags().Int64Var(&appResyncPeriod, "app-resync", int64(env.ParseDurationFromEnv("ARGOCD_RECONCILIATION_TIMEOUT", defaultAppResyncPeriod*time.Second, 0, math.MaxInt64).Seconds()), "Time period in seconds for application resync.")
command.Flags().Int64Var(&appHardResyncPeriod, "app-hard-resync", int64(env.ParseDurationFromEnv("ARGOCD_HARD_RECONCILIATION_TIMEOUT", defaultAppHardResyncPeriod*time.Second, 0, math.MaxInt64).Seconds()), "Time period in seconds for application hard resync.")
- command.Flags().Int64Var(&appResyncJitter, "app-resync-jitter", int64(env.ParseDurationFromEnv("ARGOCD_RECONCILIATION_JITTER", defaultAppResyncPeriodJitter*time.Second, 0, math.MaxInt64).Seconds()), "Maximum time period in seconds to add as a delay jitter for application resync.")
- command.Flags().Int64Var(&repoErrorGracePeriod, "repo-error-grace-period-seconds", int64(env.ParseDurationFromEnv("ARGOCD_REPO_ERROR_GRACE_PERIOD_SECONDS", defaultRepoErrorGracePeriod*time.Second, 0, math.MaxInt64).Seconds()), "Grace period in seconds for ignoring consecutive errors while communicating with repo server.")
+ command.Flags().Int64Var(&appResyncJitter, "app-resync-jitter", int64(env.ParseDurationFromEnv("ARGOCD_RECONCILIATION_JITTER", 0*time.Second, 0, math.MaxInt64).Seconds()), "Maximum time period in seconds to add as a delay jitter for application resync.")
+ command.Flags().Int64Var(&repoErrorGracePeriod, "repo-error-grace-period-seconds", int64(env.ParseDurationFromEnv("ARGOCD_REPO_ERROR_GRACE_PERIOD_SECONDS", defaultAppResyncPeriod*time.Second, 0, math.MaxInt64).Seconds()), "Grace period in seconds for ignoring consecutive errors while communicating with repo server.")
command.Flags().StringVar(&repoServerAddress, "repo-server", env.StringFromEnv("ARGOCD_APPLICATION_CONTROLLER_REPO_SERVER", common.DefaultRepoServerAddr), "Repo server address.")
command.Flags().IntVar(&repoServerTimeoutSeconds, "repo-server-timeout-seconds", env.ParseNumFromEnv("ARGOCD_APPLICATION_CONTROLLER_REPO_SERVER_TIMEOUT_SECONDS", 60, 0, math.MaxInt64), "Repo server RPC call timeout seconds.")
command.Flags().StringVar(&commitServerAddress, "commit-server", env.StringFromEnv("ARGOCD_APPLICATION_CONTROLLER_COMMIT_SERVER", common.DefaultCommitServerAddr), "Commit server address.")
command.Flags().IntVar(&statusProcessors, "status-processors", env.ParseNumFromEnv("ARGOCD_APPLICATION_CONTROLLER_STATUS_PROCESSORS", 20, 0, math.MaxInt32), "Number of application status processors")
command.Flags().IntVar(&operationProcessors, "operation-processors", env.ParseNumFromEnv("ARGOCD_APPLICATION_CONTROLLER_OPERATION_PROCESSORS", 10, 0, math.MaxInt32), "Number of application operation processors")
- command.Flags().StringVar(&cmdutil.LogFormat, "logformat", env.StringFromEnv("ARGOCD_APPLICATION_CONTROLLER_LOGFORMAT", "json"), "Set the logging format. One of: json|text")
+ command.Flags().StringVar(&cmdutil.LogFormat, "logformat", env.StringFromEnv("ARGOCD_APPLICATION_CONTROLLER_LOGFORMAT", "text"), "Set the logging format. One of: text|json")
command.Flags().StringVar(&cmdutil.LogLevel, "loglevel", env.StringFromEnv("ARGOCD_APPLICATION_CONTROLLER_LOGLEVEL", "info"), "Set the logging level. One of: debug|info|warn|error")
command.Flags().IntVar(&glogLevel, "gloglevel", 0, "Set the glog logging level")
command.Flags().IntVar(&metricsPort, "metrics-port", common.DefaultPortArgoCDMetrics, "Start metrics server on given port")
@@ -281,13 +275,12 @@ func NewCommand() *cobra.Command {
command.Flags().BoolVar(&repoServerStrictTLS, "repo-server-strict-tls", env.ParseBoolFromEnv("ARGOCD_APPLICATION_CONTROLLER_REPO_SERVER_STRICT_TLS", false), "Whether to use strict validation of the TLS cert presented by the repo server")
command.Flags().StringSliceVar(&metricsAplicationLabels, "metrics-application-labels", []string{}, "List of Application labels that will be added to the argocd_application_labels metric")
command.Flags().StringSliceVar(&metricsAplicationConditions, "metrics-application-conditions", []string{}, "List of Application conditions that will be added to the argocd_application_conditions metric")
- command.Flags().StringSliceVar(&metricsClusterLabels, "metrics-cluster-labels", []string{}, "List of Cluster labels that will be added to the argocd_cluster_labels metric")
command.Flags().StringVar(&otlpAddress, "otlp-address", env.StringFromEnv("ARGOCD_APPLICATION_CONTROLLER_OTLP_ADDRESS", ""), "OpenTelemetry collector address to send traces to")
command.Flags().BoolVar(&otlpInsecure, "otlp-insecure", env.ParseBoolFromEnv("ARGOCD_APPLICATION_CONTROLLER_OTLP_INSECURE", true), "OpenTelemetry collector insecure mode")
command.Flags().StringToStringVar(&otlpHeaders, "otlp-headers", env.ParseStringToStringFromEnv("ARGOCD_APPLICATION_CONTROLLER_OTLP_HEADERS", map[string]string{}, ","), "List of OpenTelemetry collector extra headers sent with traces, headers are comma-separated key-value pairs(e.g. key1=value1,key2=value2)")
command.Flags().StringSliceVar(&otlpAttrs, "otlp-attrs", env.StringsFromEnv("ARGOCD_APPLICATION_CONTROLLER_OTLP_ATTRS", []string{}, ","), "List of OpenTelemetry collector extra attrs when send traces, each attribute is separated by a colon(e.g. key:value)")
command.Flags().StringSliceVar(&applicationNamespaces, "application-namespaces", env.StringsFromEnv("ARGOCD_APPLICATION_NAMESPACES", []string{}, ","), "List of additional namespaces that applications are allowed to be reconciled from")
- command.Flags().BoolVar(&persistResourceHealth, "persist-resource-health", env.ParseBoolFromEnv("ARGOCD_APPLICATION_CONTROLLER_PERSIST_RESOURCE_HEALTH", false), "Enables storing the managed resources health in the Application CRD")
+ command.Flags().BoolVar(&persistResourceHealth, "persist-resource-health", env.ParseBoolFromEnv("ARGOCD_APPLICATION_CONTROLLER_PERSIST_RESOURCE_HEALTH", true), "Enables storing the managed resources health in the Application CRD")
command.Flags().StringVar(&shardingAlgorithm, "sharding-method", env.StringFromEnv(common.EnvControllerShardingAlgorithm, common.DefaultShardingAlgorithm), "Enables choice of sharding method. Supported sharding methods are : [legacy, round-robin, consistent-hashing] ")
// global queue rate limit config
command.Flags().Int64Var(&workqueueRateLimit.BucketSize, "wq-bucket-size", env.ParseInt64FromEnv("WORKQUEUE_BUCKET_SIZE", 500, 1, math.MaxInt64), "Set Workqueue Rate Limiter Bucket Size, default 500")
diff --git a/cmd/argocd-applicationset-controller/commands/applicationset_controller.go b/cmd/argocd-applicationset-controller/commands/applicationset_controller.go
index c5383ed9a7..ce7b69c69b 100644
--- a/cmd/argocd-applicationset-controller/commands/applicationset_controller.go
+++ b/cmd/argocd-applicationset-controller/commands/applicationset_controller.go
@@ -8,22 +8,22 @@ import (
"runtime/debug"
"time"
- "github.com/argoproj/pkg/v2/stats"
+ "github.com/argoproj/pkg/stats"
"k8s.io/apimachinery/pkg/runtime"
ctrl "sigs.k8s.io/controller-runtime"
- "github.com/argoproj/argo-cd/v3/reposerver/apiclient"
- logutils "github.com/argoproj/argo-cd/v3/util/log"
- "github.com/argoproj/argo-cd/v3/util/tls"
+ "github.com/argoproj/argo-cd/v2/reposerver/apiclient"
+ logutils "github.com/argoproj/argo-cd/v2/util/log"
+ "github.com/argoproj/argo-cd/v2/util/tls"
- "github.com/argoproj/argo-cd/v3/applicationset/controllers"
- "github.com/argoproj/argo-cd/v3/applicationset/generators"
- "github.com/argoproj/argo-cd/v3/applicationset/utils"
- "github.com/argoproj/argo-cd/v3/applicationset/webhook"
- cmdutil "github.com/argoproj/argo-cd/v3/cmd/util"
- "github.com/argoproj/argo-cd/v3/common"
- "github.com/argoproj/argo-cd/v3/util/env"
- "github.com/argoproj/argo-cd/v3/util/github_app"
+ "github.com/argoproj/argo-cd/v2/applicationset/controllers"
+ "github.com/argoproj/argo-cd/v2/applicationset/generators"
+ "github.com/argoproj/argo-cd/v2/applicationset/utils"
+ "github.com/argoproj/argo-cd/v2/applicationset/webhook"
+ cmdutil "github.com/argoproj/argo-cd/v2/cmd/util"
+ "github.com/argoproj/argo-cd/v2/common"
+ "github.com/argoproj/argo-cd/v2/util/env"
+ "github.com/argoproj/argo-cd/v2/util/github_app"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
@@ -36,21 +36,17 @@ import (
ctrlclient "sigs.k8s.io/controller-runtime/pkg/client"
metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server"
- appsetmetrics "github.com/argoproj/argo-cd/v3/applicationset/metrics"
- "github.com/argoproj/argo-cd/v3/applicationset/services"
- appv1alpha1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- "github.com/argoproj/argo-cd/v3/util/cli"
- "github.com/argoproj/argo-cd/v3/util/db"
- "github.com/argoproj/argo-cd/v3/util/errors"
- argosettings "github.com/argoproj/argo-cd/v3/util/settings"
+ appsetmetrics "github.com/argoproj/argo-cd/v2/applicationset/metrics"
+ "github.com/argoproj/argo-cd/v2/applicationset/services"
+ appv1alpha1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/util/cli"
+ "github.com/argoproj/argo-cd/v2/util/db"
+ "github.com/argoproj/argo-cd/v2/util/errors"
+ argosettings "github.com/argoproj/argo-cd/v2/util/settings"
)
var gitSubmoduleEnabled = env.ParseBoolFromEnv(common.EnvGitSubmoduleEnabled, true)
-const (
- cliName = common.ApplicationSetController
-)
-
func NewCommand() *cobra.Command {
var (
clientConfig clientcmd.ClientConfig
@@ -83,10 +79,9 @@ func NewCommand() *cobra.Command {
_ = clientgoscheme.AddToScheme(scheme)
_ = appv1alpha1.AddToScheme(scheme)
command := cobra.Command{
- Use: cliName,
- Short: "Starts Argo CD ApplicationSet controller",
- DisableAutoGenTag: true,
- RunE: func(c *cobra.Command, _ []string) error {
+ Use: "controller",
+ Short: "Starts Argo CD ApplicationSet controller",
+ RunE: func(c *cobra.Command, args []string) error {
ctx := c.Context()
vers := common.GetVersion()
@@ -125,7 +120,8 @@ 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]
@@ -185,15 +181,16 @@ func NewCommand() *cobra.Command {
if !repoServerPlaintext && repoServerStrictTLS {
pool, err := tls.LoadX509CertPool(
- env.StringFromEnv(common.EnvAppConfigPath, common.DefaultAppConfigPath)+"/reposerver/tls/tls.crt",
- env.StringFromEnv(common.EnvAppConfigPath, common.DefaultAppConfigPath)+"/reposerver/tls/ca.crt",
+ fmt.Sprintf("%s/reposerver/tls/tls.crt", env.StringFromEnv(common.EnvAppConfigPath, common.DefaultAppConfigPath)),
+ fmt.Sprintf("%s/reposerver/tls/ca.crt", env.StringFromEnv(common.EnvAppConfigPath, common.DefaultAppConfigPath)),
)
errors.CheckError(err)
tlsConfig.Certificates = pool
}
repoClientset := apiclient.NewRepoServerClientset(argocdRepoServer, repoServerTimeoutSeconds, tlsConfig)
- argoCDService := services.NewArgoCDService(argoCDDB, gitSubmoduleEnabled, repoClientset, enableNewGitFileGlobbing)
+ argoCDService, err := services.NewArgoCDService(argoCDDB.GetRepository, gitSubmoduleEnabled, repoClientset, enableNewGitFileGlobbing)
+ errors.CheckError(err)
topLevelGenerators := generators.GetGenerators(ctx, mgr.GetClient(), k8sClient, namespace, argoCDService, dynamicClient, scmConfig)
@@ -256,7 +253,7 @@ func NewCommand() *cobra.Command {
command.Flags().StringVar(&policy, "policy", env.StringFromEnv("ARGOCD_APPLICATIONSET_CONTROLLER_POLICY", ""), "Modify how application is synced between the generator and the cluster. Default is '' (empty), which means AppSets default to 'sync', but they may override that default. Setting an explicit value prevents AppSet-level overrides, unless --allow-policy-override is enabled. Explicit options are: 'sync' (create & update & delete), 'create-only', 'create-update' (no deletion), 'create-delete' (no update)")
command.Flags().BoolVar(&enablePolicyOverride, "enable-policy-override", env.ParseBoolFromEnv("ARGOCD_APPLICATIONSET_CONTROLLER_ENABLE_POLICY_OVERRIDE", policy == ""), "For security reason if 'policy' is set, it is not possible to override it at applicationSet level. 'allow-policy-override' allows user to define their own policy")
command.Flags().BoolVar(&debugLog, "debug", env.ParseBoolFromEnv("ARGOCD_APPLICATIONSET_CONTROLLER_DEBUG", false), "Print debug logs. Takes precedence over loglevel")
- command.Flags().StringVar(&cmdutil.LogFormat, "logformat", env.StringFromEnv("ARGOCD_APPLICATIONSET_CONTROLLER_LOGFORMAT", "json"), "Set the logging format. One of: json|text")
+ command.Flags().StringVar(&cmdutil.LogFormat, "logformat", env.StringFromEnv("ARGOCD_APPLICATIONSET_CONTROLLER_LOGFORMAT", "text"), "Set the logging format. One of: text|json")
command.Flags().StringVar(&cmdutil.LogLevel, "loglevel", env.StringFromEnv("ARGOCD_APPLICATIONSET_CONTROLLER_LOGLEVEL", "info"), "Set the logging level. One of: debug|info|warn|error")
command.Flags().StringSliceVar(&allowedScmProviders, "allowed-scm-providers", env.StringsFromEnv("ARGOCD_APPLICATIONSET_CONTROLLER_ALLOWED_SCM_PROVIDERS", []string{}, ","), "The list of allowed custom SCM provider API URLs. This restriction does not apply to SCM or PR generators which do not accept a custom API URL. (Default: Empty = all)")
command.Flags().BoolVar(&enableScmProviders, "enable-scm-providers", env.ParseBoolFromEnv("ARGOCD_APPLICATIONSET_CONTROLLER_ENABLE_SCM_PROVIDERS", true), "Enable retrieving information from SCM providers, used by the SCM and PR generators (Default: true)")
diff --git a/cmd/argocd-cmp-server/commands/argocd_cmp_server.go b/cmd/argocd-cmp-server/commands/argocd_cmp_server.go
index efb4960fae..9d1894695f 100644
--- a/cmd/argocd-cmp-server/commands/argocd_cmp_server.go
+++ b/cmd/argocd-cmp-server/commands/argocd_cmp_server.go
@@ -4,18 +4,18 @@ import (
"runtime/debug"
"time"
- "github.com/argoproj/pkg/v2/stats"
+ "github.com/argoproj/pkg/stats"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
- cmdutil "github.com/argoproj/argo-cd/v3/cmd/util"
- "github.com/argoproj/argo-cd/v3/cmpserver"
- "github.com/argoproj/argo-cd/v3/cmpserver/plugin"
- "github.com/argoproj/argo-cd/v3/common"
- "github.com/argoproj/argo-cd/v3/util/cli"
- "github.com/argoproj/argo-cd/v3/util/env"
- "github.com/argoproj/argo-cd/v3/util/errors"
- traceutil "github.com/argoproj/argo-cd/v3/util/trace"
+ cmdutil "github.com/argoproj/argo-cd/v2/cmd/util"
+ "github.com/argoproj/argo-cd/v2/cmpserver"
+ "github.com/argoproj/argo-cd/v2/cmpserver/plugin"
+ "github.com/argoproj/argo-cd/v2/common"
+ "github.com/argoproj/argo-cd/v2/util/cli"
+ "github.com/argoproj/argo-cd/v2/util/env"
+ "github.com/argoproj/argo-cd/v2/util/errors"
+ traceutil "github.com/argoproj/argo-cd/v2/util/trace"
)
const (
@@ -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, _ []string) error {
+ RunE: func(c *cobra.Command, args []string) error {
ctx := c.Context()
vers := common.GetVersion()
@@ -89,7 +89,7 @@ func NewCommand() *cobra.Command {
},
}
- command.Flags().StringVar(&cmdutil.LogFormat, "logformat", env.StringFromEnv("ARGOCD_CMP_SERVER_LOGFORMAT", "json"), "Set the logging format. One of: json|text")
+ command.Flags().StringVar(&cmdutil.LogFormat, "logformat", env.StringFromEnv("ARGOCD_CMP_SERVER_LOGFORMAT", "text"), "Set the logging format. One of: text|json")
command.Flags().StringVar(&cmdutil.LogLevel, "loglevel", env.StringFromEnv("ARGOCD_CMP_SERVER_LOGLEVEL", "info"), "Set the logging level. One of: trace|debug|info|warn|error")
command.Flags().StringVar(&configFilePath, "config-dir-path", common.DefaultPluginConfigFilePath, "Config management plugin configuration file location, Default is '/home/argocd/cmp-server/config/'")
command.Flags().StringVar(&otlpAddress, "otlp-address", env.StringFromEnv("ARGOCD_CMP_SERVER_OTLP_ADDRESS", ""), "OpenTelemetry collector address to send traces to")
diff --git a/cmd/argocd-commit-server/commands/argocd_commit_server.go b/cmd/argocd-commit-server/commands/argocd_commit_server.go
index 7feed03381..5c07bc0c14 100644
--- a/cmd/argocd-commit-server/commands/argocd_commit_server.go
+++ b/cmd/argocd-commit-server/commands/argocd_commit_server.go
@@ -13,17 +13,17 @@ import (
"github.com/spf13/cobra"
"google.golang.org/grpc/health/grpc_health_v1"
- cmdutil "github.com/argoproj/argo-cd/v3/cmd/util"
- "github.com/argoproj/argo-cd/v3/commitserver"
- "github.com/argoproj/argo-cd/v3/commitserver/apiclient"
- "github.com/argoproj/argo-cd/v3/commitserver/metrics"
- "github.com/argoproj/argo-cd/v3/common"
- "github.com/argoproj/argo-cd/v3/util/askpass"
- "github.com/argoproj/argo-cd/v3/util/cli"
- "github.com/argoproj/argo-cd/v3/util/env"
- "github.com/argoproj/argo-cd/v3/util/errors"
- "github.com/argoproj/argo-cd/v3/util/healthz"
- utilio "github.com/argoproj/argo-cd/v3/util/io"
+ cmdutil "github.com/argoproj/argo-cd/v2/cmd/util"
+ "github.com/argoproj/argo-cd/v2/commitserver"
+ "github.com/argoproj/argo-cd/v2/commitserver/apiclient"
+ "github.com/argoproj/argo-cd/v2/commitserver/metrics"
+ "github.com/argoproj/argo-cd/v2/common"
+ "github.com/argoproj/argo-cd/v2/util/askpass"
+ "github.com/argoproj/argo-cd/v2/util/cli"
+ "github.com/argoproj/argo-cd/v2/util/env"
+ "github.com/argoproj/argo-cd/v2/util/errors"
+ "github.com/argoproj/argo-cd/v2/util/healthz"
+ ioutil "github.com/argoproj/argo-cd/v2/util/io"
)
// NewCommand returns a new instance of an argocd-commit-server command
@@ -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(_ *cobra.Command, _ []string) error {
+ RunE: func(cmd *cobra.Command, args []string) error {
vers := common.GetVersion()
vers.LogStartupInfo(
"Argo CD Commit Server",
@@ -71,7 +71,7 @@ func NewCommand() *cobra.Command {
if err != nil {
return err
}
- defer utilio.Close(conn)
+ defer ioutil.Close(conn)
client := grpc_health_v1.NewHealthClient(conn)
res, err := client.Check(r.Context(), &grpc_health_v1.HealthCheckRequest{})
if err != nil {
@@ -106,7 +106,7 @@ func NewCommand() *cobra.Command {
return nil
},
}
- command.Flags().StringVar(&cmdutil.LogFormat, "logformat", env.StringFromEnv("ARGOCD_COMMIT_SERVER_LOGFORMAT", "json"), "Set the logging format. One of: json|text")
+ command.Flags().StringVar(&cmdutil.LogFormat, "logformat", env.StringFromEnv("ARGOCD_COMMIT_SERVER_LOGFORMAT", "text"), "Set the logging format. One of: text|json")
command.Flags().StringVar(&cmdutil.LogLevel, "loglevel", env.StringFromEnv("ARGOCD_COMMIT_SERVER_LOGLEVEL", "info"), "Set the logging level. One of: debug|info|warn|error")
command.Flags().StringVar(&listenHost, "address", env.StringFromEnv("ARGOCD_COMMIT_SERVER_LISTEN_ADDRESS", common.DefaultAddressCommitServer), "Listen on given address for incoming connections")
command.Flags().IntVar(&listenPort, "port", common.DefaultPortCommitServer, "Listen on given port for incoming connections")
diff --git a/cmd/argocd-dex/commands/argocd_dex.go b/cmd/argocd-dex/commands/argocd_dex.go
index 8afcb7955e..f674266738 100644
--- a/cmd/argocd-dex/commands/argocd_dex.go
+++ b/cmd/argocd-dex/commands/argocd_dex.go
@@ -7,7 +7,7 @@ import (
"runtime/debug"
"syscall"
- "github.com/argoproj/argo-cd/v3/common"
+ "github.com/argoproj/argo-cd/v2/common"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
@@ -15,13 +15,13 @@ import (
"k8s.io/client-go/tools/clientcmd"
"sigs.k8s.io/yaml"
- cmdutil "github.com/argoproj/argo-cd/v3/cmd/util"
- "github.com/argoproj/argo-cd/v3/util/cli"
- "github.com/argoproj/argo-cd/v3/util/dex"
- "github.com/argoproj/argo-cd/v3/util/env"
- "github.com/argoproj/argo-cd/v3/util/errors"
- "github.com/argoproj/argo-cd/v3/util/settings"
- "github.com/argoproj/argo-cd/v3/util/tls"
+ cmdutil "github.com/argoproj/argo-cd/v2/cmd/util"
+ "github.com/argoproj/argo-cd/v2/util/cli"
+ "github.com/argoproj/argo-cd/v2/util/dex"
+ "github.com/argoproj/argo-cd/v2/util/env"
+ "github.com/argoproj/argo-cd/v2/util/errors"
+ "github.com/argoproj/argo-cd/v2/util/settings"
+ "github.com/argoproj/argo-cd/v2/util/tls"
)
const (
@@ -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, _ []string) error {
+ RunE: func(c *cobra.Command, args []string) error {
ctx := c.Context()
vers := common.GetVersion()
@@ -136,15 +136,16 @@ func NewRunDexCommand() *cobra.Command {
errors.CheckError(err)
}
break
+ } else {
+ log.Infof("dex config unmodified")
}
- log.Infof("dex config unmodified")
}
}
},
}
clientConfig = cli.AddKubectlFlagsToCmd(&command)
- command.Flags().StringVar(&cmdutil.LogFormat, "logformat", env.StringFromEnv("ARGOCD_DEX_SERVER_LOGFORMAT", "json"), "Set the logging format. One of: json|text")
+ command.Flags().StringVar(&cmdutil.LogFormat, "logformat", env.StringFromEnv("ARGOCD_DEX_SERVER_LOGFORMAT", "text"), "Set the logging format. One of: text|json")
command.Flags().StringVar(&cmdutil.LogLevel, "loglevel", env.StringFromEnv("ARGOCD_DEX_SERVER_LOGLEVEL", "info"), "Set the logging level. One of: debug|info|warn|error")
command.Flags().BoolVar(&disableTLS, "disable-tls", env.ParseBoolFromEnv("ARGOCD_DEX_SERVER_DISABLE_TLS", false), "Disable TLS on the HTTP endpoint")
return &command
@@ -159,7 +160,7 @@ func NewGenDexConfigCommand() *cobra.Command {
command := cobra.Command{
Use: "gendexcfg",
Short: "Generates a dex config from Argo CD settings",
- RunE: func(c *cobra.Command, _ []string) error {
+ RunE: func(c *cobra.Command, args []string) error {
ctx := c.Context()
cli.SetLogFormat(cmdutil.LogFormat)
@@ -180,14 +181,14 @@ func NewGenDexConfigCommand() *cobra.Command {
return nil
}
if out == "" {
- dexCfg := make(map[string]any)
+ dexCfg := make(map[string]interface{})
err := yaml.Unmarshal(dexCfgBytes, &dexCfg)
errors.CheckError(err)
if staticClientsInterface, ok := dexCfg["staticClients"]; ok {
- if staticClients, ok := staticClientsInterface.([]any); ok {
+ if staticClients, ok := staticClientsInterface.([]interface{}); ok {
for i := range staticClients {
staticClient := staticClients[i]
- if mappings, ok := staticClient.(map[string]any); ok {
+ if mappings, ok := staticClient.(map[string]interface{}); ok {
for key := range mappings {
if key == "secret" {
mappings[key] = "******"
@@ -212,15 +213,15 @@ func NewGenDexConfigCommand() *cobra.Command {
}
clientConfig = cli.AddKubectlFlagsToCmd(&command)
- command.Flags().StringVar(&cmdutil.LogFormat, "logformat", env.StringFromEnv("ARGOCD_DEX_SERVER_LOGFORMAT", "json"), "Set the logging format. One of: json|text")
+ command.Flags().StringVar(&cmdutil.LogFormat, "logformat", env.StringFromEnv("ARGOCD_DEX_SERVER_LOGFORMAT", "text"), "Set the logging format. One of: text|json")
command.Flags().StringVar(&cmdutil.LogLevel, "loglevel", env.StringFromEnv("ARGOCD_DEX_SERVER_LOGLEVEL", "info"), "Set the logging level. One of: debug|info|warn|error")
command.Flags().StringVarP(&out, "out", "o", "", "Output to the specified file instead of stdout")
command.Flags().BoolVar(&disableTLS, "disable-tls", env.ParseBoolFromEnv("ARGOCD_DEX_SERVER_DISABLE_TLS", false), "Disable TLS on the HTTP endpoint")
return &command
}
-func iterateStringFields(obj any, callback func(name string, val string) string) {
- if mapField, ok := obj.(map[string]any); ok {
+func iterateStringFields(obj interface{}, callback func(name string, val string) string) {
+ if mapField, ok := obj.(map[string]interface{}); ok {
for field, val := range mapField {
if strVal, ok := val.(string); ok {
mapField[field] = callback(field, strVal)
@@ -228,7 +229,7 @@ func iterateStringFields(obj any, callback func(name string, val string) string)
iterateStringFields(val, callback)
}
}
- } else if arrayField, ok := obj.([]any); ok {
+ } else if arrayField, ok := obj.([]interface{}); ok {
for i := range arrayField {
iterateStringFields(arrayField[i], callback)
}
@@ -236,14 +237,15 @@ func iterateStringFields(obj any, callback func(name string, val string) string)
}
func redactor(dirtyString string) string {
- config := make(map[string]any)
+ config := make(map[string]interface{})
err := yaml.Unmarshal([]byte(dirtyString), &config)
errors.CheckError(err)
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-git-ask-pass/commands/argocd_git_ask_pass.go b/cmd/argocd-git-ask-pass/commands/argocd_git_ask_pass.go
index b4780e2515..73673e977b 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
@@ -9,10 +9,10 @@ import (
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
- "github.com/argoproj/argo-cd/v3/util/askpass"
- "github.com/argoproj/argo-cd/v3/util/errors"
- grpc_util "github.com/argoproj/argo-cd/v3/util/grpc"
- utilio "github.com/argoproj/argo-cd/v3/util/io"
+ "github.com/argoproj/argo-cd/v2/util/askpass"
+ "github.com/argoproj/argo-cd/v2/util/errors"
+ grpc_util "github.com/argoproj/argo-cd/v2/util/grpc"
+ "github.com/argoproj/argo-cd/v2/util/io"
)
const (
@@ -25,7 +25,7 @@ func NewCommand() *cobra.Command {
Use: cliName,
Short: "Argo CD git credential helper",
DisableAutoGenTag: true,
- Run: func(c *cobra.Command, _ []string) {
+ Run: func(c *cobra.Command, args []string) {
ctx := c.Context()
if len(os.Args) != 2 {
@@ -37,7 +37,7 @@ func NewCommand() *cobra.Command {
}
conn, err := grpc_util.BlockingDial(ctx, "unix", askpass.SocketPath, nil, grpc.WithTransportCredentials(insecure.NewCredentials()))
errors.CheckError(err)
- defer utilio.Close(conn)
+ defer io.Close(conn)
client := askpass.NewAskPassServiceClient(conn)
creds, err := client.GetCredentials(ctx, &askpass.CredentialsRequest{Nonce: nonce})
diff --git a/cmd/argocd-k8s-auth/commands/aws.go b/cmd/argocd-k8s-auth/commands/aws.go
index 6052bdb4dc..1794a5bf57 100644
--- a/cmd/argocd-k8s-auth/commands/aws.go
+++ b/cmd/argocd-k8s-auth/commands/aws.go
@@ -16,7 +16,7 @@ import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
clientauthv1beta1 "k8s.io/client-go/pkg/apis/clientauthentication/v1beta1"
- "github.com/argoproj/argo-cd/v3/util/errors"
+ "github.com/argoproj/argo-cd/v2/util/errors"
)
const (
@@ -41,7 +41,7 @@ func newAWSCommand() *cobra.Command {
)
command := &cobra.Command{
Use: "aws",
- Run: func(c *cobra.Command, _ []string) {
+ Run: func(c *cobra.Command, args []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 e9dd42aa9e..7e31e50efb 100644
--- a/cmd/argocd-k8s-auth/commands/aws_test.go
+++ b/cmd/argocd-k8s-auth/commands/aws_test.go
@@ -1,7 +1,8 @@
package commands
import (
- "errors"
+ "context"
+ "fmt"
"testing"
"time"
@@ -10,13 +11,13 @@ import (
)
func TestGetSignedRequestWithRetry(t *testing.T) {
- ctx := t.Context()
+ ctx := context.Background()
t.Run("will return signed request on first attempt", func(t *testing.T) {
// given
t.Parallel()
mock := &signedRequestMock{
- returnFunc: func(_ *signedRequestMock) (string, error) {
+ returnFunc: func(m *signedRequestMock) (string, error) {
return "token", nil
},
}
@@ -34,7 +35,7 @@ func TestGetSignedRequestWithRetry(t *testing.T) {
mock := &signedRequestMock{
returnFunc: func(m *signedRequestMock) (string, error) {
if m.getSignedRequestCalls < 3 {
- return "", errors.New("some error")
+ return "", fmt.Errorf("some error")
}
return "token", nil
},
@@ -51,8 +52,8 @@ func TestGetSignedRequestWithRetry(t *testing.T) {
// given
t.Parallel()
mock := &signedRequestMock{
- returnFunc: func(_ *signedRequestMock) (string, error) {
- return "", errors.New("some error")
+ returnFunc: func(m *signedRequestMock) (string, error) {
+ return "", fmt.Errorf("some error")
},
}
@@ -61,7 +62,7 @@ func TestGetSignedRequestWithRetry(t *testing.T) {
// then
require.Error(t, err)
- assert.Empty(t, signed)
+ assert.Equal(t, "", signed)
})
}
@@ -70,7 +71,7 @@ type signedRequestMock struct {
returnFunc func(m *signedRequestMock) (string, error)
}
-func (m *signedRequestMock) getSignedRequestMock(_, _ string, _ string) (string, error) {
+func (m *signedRequestMock) getSignedRequestMock(clusterName, roleARN string, profile 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 357144c5ad..287b8d457a 100644
--- a/cmd/argocd-k8s-auth/commands/azure.go
+++ b/cmd/argocd-k8s-auth/commands/azure.go
@@ -7,7 +7,7 @@ import (
"github.com/Azure/kubelogin/pkg/token"
"github.com/spf13/cobra"
- "github.com/argoproj/argo-cd/v3/util/errors"
+ "github.com/argoproj/argo-cd/v2/util/errors"
)
var (
@@ -22,7 +22,7 @@ const (
func newAzureCommand() *cobra.Command {
command := &cobra.Command{
Use: "azure",
- Run: func(c *cobra.Command, _ []string) {
+ Run: func(c *cobra.Command, args []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 d45cffd20d..388d274072 100644
--- a/cmd/argocd-k8s-auth/commands/gcp.go
+++ b/cmd/argocd-k8s-auth/commands/gcp.go
@@ -7,7 +7,7 @@ import (
"github.com/spf13/cobra"
"golang.org/x/oauth2/google"
- "github.com/argoproj/argo-cd/v3/util/errors"
+ "github.com/argoproj/argo-cd/v2/util/errors"
)
// defaultGCPScopes:
@@ -24,7 +24,7 @@ var defaultGCPScopes = []string{
func newGCPCommand() *cobra.Command {
command := &cobra.Command{
Use: "gcp",
- Run: func(c *cobra.Command, _ []string) {
+ Run: func(c *cobra.Command, args []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 de29571fab..6f2dcc86a5 100644
--- a/cmd/argocd-notification/commands/controller.go
+++ b/cmd/argocd-notification/commands/controller.go
@@ -11,15 +11,15 @@ import (
"sync"
"syscall"
- "github.com/argoproj/argo-cd/v3/common"
- "github.com/argoproj/argo-cd/v3/reposerver/apiclient"
+ "github.com/argoproj/argo-cd/v2/common"
+ "github.com/argoproj/argo-cd/v2/reposerver/apiclient"
- "github.com/argoproj/argo-cd/v3/util/env"
- "github.com/argoproj/argo-cd/v3/util/errors"
- service "github.com/argoproj/argo-cd/v3/util/notification/argocd"
- "github.com/argoproj/argo-cd/v3/util/tls"
+ "github.com/argoproj/argo-cd/v2/util/env"
+ "github.com/argoproj/argo-cd/v2/util/errors"
+ service "github.com/argoproj/argo-cd/v2/util/notification/argocd"
+ "github.com/argoproj/argo-cd/v2/util/tls"
- notificationscontroller "github.com/argoproj/argo-cd/v3/notification_controller/controller"
+ notificationscontroller "github.com/argoproj/argo-cd/v2/notification_controller/controller"
"github.com/argoproj/notifications-engine/pkg/controller"
"github.com/prometheus/client_golang/prometheus"
@@ -66,7 +66,7 @@ func NewCommand() *cobra.Command {
command := cobra.Command{
Use: "controller",
Short: "Starts Argo CD Notifications controller",
- RunE: func(_ *cobra.Command, _ []string) error {
+ RunE: func(c *cobra.Command, args []string) error {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
@@ -129,8 +129,8 @@ func NewCommand() *cobra.Command {
}
if !tlsConfig.DisableTLS && tlsConfig.StrictValidation {
pool, err := tls.LoadX509CertPool(
- env.StringFromEnv(common.EnvAppConfigPath, common.DefaultAppConfigPath)+"/reposerver/tls/tls.crt",
- env.StringFromEnv(common.EnvAppConfigPath, common.DefaultAppConfigPath)+"/reposerver/tls/ca.crt",
+ fmt.Sprintf("%s/reposerver/tls/tls.crt", env.StringFromEnv(common.EnvAppConfigPath, common.DefaultAppConfigPath)),
+ fmt.Sprintf("%s/reposerver/tls/ca.crt", env.StringFromEnv(common.EnvAppConfigPath, common.DefaultAppConfigPath)),
)
if err != nil {
return fmt.Errorf("failed to load repo-server certificate pool: %w", err)
@@ -180,7 +180,7 @@ func NewCommand() *cobra.Command {
command.Flags().StringVar(&appLabelSelector, "app-label-selector", "", "App label selector.")
command.Flags().StringVar(&namespace, "namespace", "", "Namespace which controller handles. Current namespace if empty.")
command.Flags().StringVar(&logLevel, "loglevel", env.StringFromEnv("ARGOCD_NOTIFICATIONS_CONTROLLER_LOGLEVEL", "info"), "Set the logging level. One of: debug|info|warn|error")
- command.Flags().StringVar(&logFormat, "logformat", env.StringFromEnv("ARGOCD_NOTIFICATIONS_CONTROLLER_LOGFORMAT", "json"), "Set the logging format. One of: json|text")
+ command.Flags().StringVar(&logFormat, "logformat", env.StringFromEnv("ARGOCD_NOTIFICATIONS_CONTROLLER_LOGFORMAT", "text"), "Set the logging format. One of: text|json")
command.Flags().IntVar(&metricsPort, "metrics-port", defaultMetricsPort, "Metrics port")
command.Flags().StringVar(&argocdRepoServer, "argocd-repo-server", common.DefaultRepoServerAddr, "Argo CD repo server address")
command.Flags().BoolVar(&argocdRepoServerPlaintext, "argocd-repo-server-plaintext", env.ParseBoolFromEnv("ARGOCD_NOTIFICATION_CONTROLLER_REPO_SERVER_PLAINTEXT", false), "Use a plaintext client (non-TLS) to connect to repository server")
diff --git a/cmd/argocd-repo-server/commands/argocd_repo_server.go b/cmd/argocd-repo-server/commands/argocd_repo_server.go
index fd8e0bd0be..19d9a2a1e4 100644
--- a/cmd/argocd-repo-server/commands/argocd_repo_server.go
+++ b/cmd/argocd-repo-server/commands/argocd_repo_server.go
@@ -12,30 +12,30 @@ import (
"syscall"
"time"
- "github.com/argoproj/pkg/v2/stats"
+ "github.com/argoproj/pkg/stats"
"github.com/redis/go-redis/v9"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"google.golang.org/grpc/health/grpc_health_v1"
"k8s.io/apimachinery/pkg/api/resource"
- cmdutil "github.com/argoproj/argo-cd/v3/cmd/util"
- "github.com/argoproj/argo-cd/v3/common"
- "github.com/argoproj/argo-cd/v3/reposerver"
- "github.com/argoproj/argo-cd/v3/reposerver/apiclient"
- reposervercache "github.com/argoproj/argo-cd/v3/reposerver/cache"
- "github.com/argoproj/argo-cd/v3/reposerver/metrics"
- "github.com/argoproj/argo-cd/v3/reposerver/repository"
- "github.com/argoproj/argo-cd/v3/util/askpass"
- cacheutil "github.com/argoproj/argo-cd/v3/util/cache"
- "github.com/argoproj/argo-cd/v3/util/cli"
- "github.com/argoproj/argo-cd/v3/util/env"
- "github.com/argoproj/argo-cd/v3/util/errors"
- "github.com/argoproj/argo-cd/v3/util/gpg"
- "github.com/argoproj/argo-cd/v3/util/healthz"
- utilio "github.com/argoproj/argo-cd/v3/util/io"
- "github.com/argoproj/argo-cd/v3/util/tls"
- traceutil "github.com/argoproj/argo-cd/v3/util/trace"
+ cmdutil "github.com/argoproj/argo-cd/v2/cmd/util"
+ "github.com/argoproj/argo-cd/v2/common"
+ "github.com/argoproj/argo-cd/v2/reposerver"
+ "github.com/argoproj/argo-cd/v2/reposerver/apiclient"
+ reposervercache "github.com/argoproj/argo-cd/v2/reposerver/cache"
+ "github.com/argoproj/argo-cd/v2/reposerver/metrics"
+ "github.com/argoproj/argo-cd/v2/reposerver/repository"
+ "github.com/argoproj/argo-cd/v2/util/askpass"
+ cacheutil "github.com/argoproj/argo-cd/v2/util/cache"
+ "github.com/argoproj/argo-cd/v2/util/cli"
+ "github.com/argoproj/argo-cd/v2/util/env"
+ "github.com/argoproj/argo-cd/v2/util/errors"
+ "github.com/argoproj/argo-cd/v2/util/gpg"
+ "github.com/argoproj/argo-cd/v2/util/healthz"
+ ioutil "github.com/argoproj/argo-cd/v2/util/io"
+ "github.com/argoproj/argo-cd/v2/util/tls"
+ traceutil "github.com/argoproj/argo-cd/v2/util/trace"
)
const (
@@ -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, _ []string) error {
+ RunE: func(c *cobra.Command, args []string) error {
ctx := c.Context()
vers := common.GetVersion()
@@ -172,7 +172,7 @@ func NewCommand() *cobra.Command {
if err != nil {
return err
}
- defer utilio.Close(conn)
+ defer ioutil.Close(conn)
client := grpc_health_v1.NewHealthClient(conn)
res, err := client.Check(r.Context(), &grpc_health_v1.HealthCheckRequest{})
if err != nil {
@@ -230,7 +230,7 @@ func NewCommand() *cobra.Command {
return nil
},
}
- command.Flags().StringVar(&cmdutil.LogFormat, "logformat", env.StringFromEnv("ARGOCD_REPO_SERVER_LOGFORMAT", "json"), "Set the logging format. One of: json|text")
+ command.Flags().StringVar(&cmdutil.LogFormat, "logformat", env.StringFromEnv("ARGOCD_REPO_SERVER_LOGFORMAT", "text"), "Set the logging format. One of: text|json")
command.Flags().StringVar(&cmdutil.LogLevel, "loglevel", env.StringFromEnv("ARGOCD_REPO_SERVER_LOGLEVEL", "info"), "Set the logging level. One of: debug|info|warn|error")
command.Flags().Int64Var(¶llelismLimit, "parallelismlimit", int64(env.ParseNumFromEnv("ARGOCD_REPO_SERVER_PARALLELISM_LIMIT", 0, 0, math.MaxInt32)), "Limit on number of concurrent manifests generate requests. Any value less the 1 means no limit.")
command.Flags().StringVar(&listenHost, "address", env.StringFromEnv("ARGOCD_REPO_SERVER_LISTEN_ADDRESS", common.DefaultAddressRepoServer), "Listen on given address for incoming connections")
diff --git a/cmd/argocd-server/commands/argocd_server.go b/cmd/argocd-server/commands/argocd_server.go
index 973cd0a182..0b89dad23e 100644
--- a/cmd/argocd-server/commands/argocd_server.go
+++ b/cmd/argocd-server/commands/argocd_server.go
@@ -12,7 +12,7 @@ import (
"k8s.io/apimachinery/pkg/runtime"
clientgoscheme "k8s.io/client-go/kubernetes/scheme"
- "github.com/argoproj/pkg/v2/stats"
+ "github.com/argoproj/pkg/stats"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"k8s.io/client-go/dynamic"
@@ -20,24 +20,24 @@ import (
"k8s.io/client-go/tools/clientcmd"
"sigs.k8s.io/controller-runtime/pkg/client"
- cmdutil "github.com/argoproj/argo-cd/v3/cmd/util"
- "github.com/argoproj/argo-cd/v3/common"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- appclientset "github.com/argoproj/argo-cd/v3/pkg/client/clientset/versioned"
- "github.com/argoproj/argo-cd/v3/reposerver/apiclient"
- reposervercache "github.com/argoproj/argo-cd/v3/reposerver/cache"
- "github.com/argoproj/argo-cd/v3/server"
- servercache "github.com/argoproj/argo-cd/v3/server/cache"
- "github.com/argoproj/argo-cd/v3/util/argo"
- cacheutil "github.com/argoproj/argo-cd/v3/util/cache"
- "github.com/argoproj/argo-cd/v3/util/cli"
- "github.com/argoproj/argo-cd/v3/util/dex"
- "github.com/argoproj/argo-cd/v3/util/env"
- "github.com/argoproj/argo-cd/v3/util/errors"
- "github.com/argoproj/argo-cd/v3/util/kube"
- "github.com/argoproj/argo-cd/v3/util/templates"
- "github.com/argoproj/argo-cd/v3/util/tls"
- traceutil "github.com/argoproj/argo-cd/v3/util/trace"
+ cmdutil "github.com/argoproj/argo-cd/v2/cmd/util"
+ "github.com/argoproj/argo-cd/v2/common"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+ appclientset "github.com/argoproj/argo-cd/v2/pkg/client/clientset/versioned"
+ "github.com/argoproj/argo-cd/v2/reposerver/apiclient"
+ reposervercache "github.com/argoproj/argo-cd/v2/reposerver/cache"
+ "github.com/argoproj/argo-cd/v2/server"
+ servercache "github.com/argoproj/argo-cd/v2/server/cache"
+ "github.com/argoproj/argo-cd/v2/util/argo"
+ cacheutil "github.com/argoproj/argo-cd/v2/util/cache"
+ "github.com/argoproj/argo-cd/v2/util/cli"
+ "github.com/argoproj/argo-cd/v2/util/dex"
+ "github.com/argoproj/argo-cd/v2/util/env"
+ "github.com/argoproj/argo-cd/v2/util/errors"
+ "github.com/argoproj/argo-cd/v2/util/kube"
+ "github.com/argoproj/argo-cd/v2/util/templates"
+ "github.com/argoproj/argo-cd/v2/util/tls"
+ traceutil "github.com/argoproj/argo-cd/v2/util/trace"
)
const (
@@ -88,7 +88,6 @@ func NewCommand() *cobra.Command {
enableProxyExtension bool
webhookParallelism int
hydratorEnabled bool
- syncWithReplaceAllowed bool
// ApplicationSet
enableNewGitFileGlobbing bool
@@ -104,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, _ []string) {
+ Run: func(c *cobra.Command, args []string) {
ctx := c.Context()
vers := common.GetVersion()
@@ -171,8 +170,8 @@ func NewCommand() *cobra.Command {
// repository server, if strict TLS validation was requested.
if !repoServerPlaintext && repoServerStrictTLS {
pool, err := tls.LoadX509CertPool(
- env.StringFromEnv(common.EnvAppConfigPath, common.DefaultAppConfigPath)+"/server/tls/tls.crt",
- env.StringFromEnv(common.EnvAppConfigPath, common.DefaultAppConfigPath)+"/server/tls/ca.crt",
+ fmt.Sprintf("%s/server/tls/tls.crt", env.StringFromEnv(common.EnvAppConfigPath, common.DefaultAppConfigPath)),
+ fmt.Sprintf("%s/server/tls/ca.crt", env.StringFromEnv(common.EnvAppConfigPath, common.DefaultAppConfigPath)),
)
if err != nil {
log.Fatalf("%v", err)
@@ -180,26 +179,26 @@ func NewCommand() *cobra.Command {
tlsConfig.Certificates = pool
}
- dexTLSConfig := &dex.DexTLSConfig{
+ dexTlsConfig := &dex.DexTLSConfig{
DisableTLS: dexServerPlaintext,
StrictValidation: dexServerStrictTLS,
}
if !dexServerPlaintext && dexServerStrictTLS {
pool, err := tls.LoadX509CertPool(
- env.StringFromEnv(common.EnvAppConfigPath, common.DefaultAppConfigPath) + "/dex/tls/ca.crt",
+ fmt.Sprintf("%s/dex/tls/ca.crt", env.StringFromEnv(common.EnvAppConfigPath, common.DefaultAppConfigPath)),
)
if err != nil {
log.Fatalf("%v", err)
}
- dexTLSConfig.RootCAs = pool
+ dexTlsConfig.RootCAs = pool
cert, err := tls.LoadX509Cert(
- env.StringFromEnv(common.EnvAppConfigPath, common.DefaultAppConfigPath) + "/dex/tls/tls.crt",
+ fmt.Sprintf("%s/dex/tls/tls.crt", env.StringFromEnv(common.EnvAppConfigPath, common.DefaultAppConfigPath)),
)
if err != nil {
log.Fatalf("%v", err)
}
- dexTLSConfig.Certificate = cert.Raw
+ dexTlsConfig.Certificate = cert.Raw
}
repoclientset := apiclient.NewRepoServerClientset(repoServerAddress, repoServerTimeoutSeconds, tlsConfig)
@@ -230,7 +229,7 @@ func NewCommand() *cobra.Command {
AppClientset: appClientSet,
RepoClientset: repoclientset,
DexServerAddr: dexServerAddress,
- DexTLSConfig: dexTLSConfig,
+ DexTLSConfig: dexTlsConfig,
DisableAuth: disableAuth,
ContentTypes: contentTypesList,
EnableGZip: enableGZip,
@@ -246,7 +245,6 @@ func NewCommand() *cobra.Command {
WebhookParallelism: webhookParallelism,
EnableK8sEvent: enableK8sEvent,
HydratorEnabled: hydratorEnabled,
- SyncWithReplaceAllowed: syncWithReplaceAllowed,
}
appsetOpts := server.ApplicationSetOpts{
@@ -297,7 +295,7 @@ func NewCommand() *cobra.Command {
command.Flags().StringVar(&staticAssetsDir, "staticassets", env.StringFromEnv("ARGOCD_SERVER_STATIC_ASSETS", "/shared/app"), "Directory path that contains additional static assets")
command.Flags().StringVar(&baseHRef, "basehref", env.StringFromEnv("ARGOCD_SERVER_BASEHREF", "/"), "Value for base href in index.html. Used if Argo CD is running behind reverse proxy under subpath different from /")
command.Flags().StringVar(&rootPath, "rootpath", env.StringFromEnv("ARGOCD_SERVER_ROOTPATH", ""), "Used if Argo CD is running behind reverse proxy under subpath different from /")
- command.Flags().StringVar(&cmdutil.LogFormat, "logformat", env.StringFromEnv("ARGOCD_SERVER_LOGFORMAT", "json"), "Set the logging format. One of: json|text")
+ command.Flags().StringVar(&cmdutil.LogFormat, "logformat", env.StringFromEnv("ARGOCD_SERVER_LOGFORMAT", "text"), "Set the logging format. One of: text|json")
command.Flags().StringVar(&cmdutil.LogLevel, "loglevel", env.StringFromEnv("ARGOCD_SERVER_LOG_LEVEL", "info"), "Set the logging level. One of: debug|info|warn|error")
command.Flags().IntVar(&glogLevel, "gloglevel", 0, "Set the glog logging level")
command.Flags().StringVar(&repoServerAddress, "repo-server", env.StringFromEnv("ARGOCD_SERVER_REPO_SERVER", common.DefaultRepoServerAddr), "Repo server address")
@@ -326,7 +324,6 @@ func NewCommand() *cobra.Command {
command.Flags().IntVar(&webhookParallelism, "webhook-parallelism-limit", env.ParseNumFromEnv("ARGOCD_SERVER_WEBHOOK_PARALLELISM_LIMIT", 50, 1, 1000), "Number of webhook requests processed concurrently")
command.Flags().StringSliceVar(&enableK8sEvent, "enable-k8s-event", env.StringsFromEnv("ARGOCD_ENABLE_K8S_EVENT", argo.DefaultEnableEventList(), ","), "Enable ArgoCD to use k8s event. For disabling all events, set the value as `none`. (e.g --enable-k8s-event=none), For enabling specific events, set the value as `event reason`. (e.g --enable-k8s-event=StatusRefreshed,ResourceCreated)")
command.Flags().BoolVar(&hydratorEnabled, "hydrator-enabled", env.ParseBoolFromEnv("ARGOCD_HYDRATOR_ENABLED", false), "Feature flag to enable Hydrator. Default (\"false\")")
- command.Flags().BoolVar(&syncWithReplaceAllowed, "sync-with-replace-allowed", env.ParseBoolFromEnv("ARGOCD_SYNC_WITH_REPLACE_ALLOWED", true), "Whether to allow users to select replace for syncs from UI/CLI")
// Flags related to the applicationSet component.
command.Flags().StringVar(&scmRootCAPath, "appset-scm-root-ca-path", env.StringFromEnv("ARGOCD_APPLICATIONSET_CONTROLLER_SCM_ROOT_CA_PATH", ""), "Provide Root CA Path for self-signed TLS Certificates")
diff --git a/cmd/argocd/commands/account.go b/cmd/argocd/commands/account.go
index d4b4a14c50..1c7298e99a 100644
--- a/cmd/argocd/commands/account.go
+++ b/cmd/argocd/commands/account.go
@@ -10,25 +10,25 @@ import (
"text/tabwriter"
"time"
- timeutil "github.com/argoproj/pkg/v2/time"
+ timeutil "github.com/argoproj/pkg/time"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"golang.org/x/term"
"sigs.k8s.io/yaml"
- "github.com/argoproj/argo-cd/v3/util/rbac"
+ "github.com/argoproj/argo-cd/v2/util/rbac"
- "github.com/argoproj/argo-cd/v3/cmd/argocd/commands/headless"
- "github.com/argoproj/argo-cd/v3/cmd/argocd/commands/utils"
- argocdclient "github.com/argoproj/argo-cd/v3/pkg/apiclient"
- accountpkg "github.com/argoproj/argo-cd/v3/pkg/apiclient/account"
- "github.com/argoproj/argo-cd/v3/pkg/apiclient/session"
- "github.com/argoproj/argo-cd/v3/util/cli"
- "github.com/argoproj/argo-cd/v3/util/errors"
- utilio "github.com/argoproj/argo-cd/v3/util/io"
- "github.com/argoproj/argo-cd/v3/util/localconfig"
- sessionutil "github.com/argoproj/argo-cd/v3/util/session"
- "github.com/argoproj/argo-cd/v3/util/templates"
+ "github.com/argoproj/argo-cd/v2/cmd/argocd/commands/headless"
+ "github.com/argoproj/argo-cd/v2/cmd/argocd/commands/utils"
+ argocdclient "github.com/argoproj/argo-cd/v2/pkg/apiclient"
+ accountpkg "github.com/argoproj/argo-cd/v2/pkg/apiclient/account"
+ "github.com/argoproj/argo-cd/v2/pkg/apiclient/session"
+ "github.com/argoproj/argo-cd/v2/util/cli"
+ "github.com/argoproj/argo-cd/v2/util/errors"
+ "github.com/argoproj/argo-cd/v2/util/io"
+ "github.com/argoproj/argo-cd/v2/util/localconfig"
+ sessionutil "github.com/argoproj/argo-cd/v2/util/session"
+ "github.com/argoproj/argo-cd/v2/util/templates"
)
func NewAccountCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command {
@@ -94,7 +94,7 @@ has appropriate RBAC permissions to change other accounts.
}
acdClient := headless.NewClientOrDie(clientOpts, c)
conn, usrIf := acdClient.NewAccountClientOrDie()
- defer utilio.Close(conn)
+ defer io.Close(conn)
userInfo := getCurrentAccount(ctx, acdClient)
@@ -173,7 +173,7 @@ func NewAccountGetUserInfoCommand(clientOpts *argocdclient.ClientOptions) *cobra
}
conn, client := headless.NewClientOrDie(clientOpts, c).NewSessionClientOrDie()
- defer utilio.Close(conn)
+ defer io.Close(conn)
response, err := client.GetUserInfo(ctx, &session.GetUserInfoRequest{})
errors.CheckError(err)
@@ -229,7 +229,7 @@ Resources: %v
}
conn, client := headless.NewClientOrDie(clientOpts, c).NewAccountClientOrDie()
- defer utilio.Close(conn)
+ defer io.Close(conn)
response, err := client.CanI(ctx, &accountpkg.CanIRequest{
Action: args[0],
@@ -267,7 +267,7 @@ func NewAccountListCommand(clientOpts *argocdclient.ClientOptions) *cobra.Comman
ctx := c.Context()
conn, client := headless.NewClientOrDie(clientOpts, c).NewAccountClientOrDie()
- defer utilio.Close(conn)
+ defer io.Close(conn)
response, err := client.ListAccounts(ctx, &accountpkg.ListAccountRequest{})
@@ -291,7 +291,7 @@ func NewAccountListCommand(clientOpts *argocdclient.ClientOptions) *cobra.Comman
func getCurrentAccount(ctx context.Context, clientset argocdclient.Client) session.GetUserInfoResponse {
conn, client := clientset.NewSessionClientOrDie()
- defer utilio.Close(conn)
+ defer io.Close(conn)
userInfo, err := client.GetUserInfo(ctx, &session.GetUserInfoRequest{})
errors.CheckError(err)
return *userInfo
@@ -320,7 +320,7 @@ argocd account get --account `,
}
conn, client := clientset.NewAccountClientOrDie()
- defer utilio.Close(conn)
+ defer io.Close(conn)
acc, err := client.GetAccount(ctx, &accountpkg.GetAccountRequest{Name: account})
@@ -388,7 +388,7 @@ argocd account generate-token --account `,
clientset := headless.NewClientOrDie(clientOpts, c)
conn, client := clientset.NewAccountClientOrDie()
- defer utilio.Close(conn)
+ defer io.Close(conn)
if account == "" {
account = getCurrentAccount(ctx, clientset).Username
}
@@ -430,7 +430,7 @@ argocd account delete-token --account ID`,
clientset := headless.NewClientOrDie(clientOpts, c)
conn, client := clientset.NewAccountClientOrDie()
- defer utilio.Close(conn)
+ defer io.Close(conn)
if account == "" {
account = getCurrentAccount(ctx, clientset).Username
}
diff --git a/cmd/argocd/commands/admin/admin.go b/cmd/argocd/commands/admin/admin.go
index cdf04597e6..6c120bd425 100644
--- a/cmd/argocd/commands/admin/admin.go
+++ b/cmd/argocd/commands/admin/admin.go
@@ -6,28 +6,28 @@ import (
"strings"
"github.com/spf13/cobra"
- corev1 "k8s.io/api/core/v1"
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+ apiv1 "k8s.io/api/core/v1"
+ v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
+ "sigs.k8s.io/yaml"
- cmdutil "github.com/argoproj/argo-cd/v3/cmd/util"
- "github.com/argoproj/argo-cd/v3/common"
- argocdclient "github.com/argoproj/argo-cd/v3/pkg/apiclient"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application"
- "github.com/argoproj/argo-cd/v3/util/errors"
+ cmdutil "github.com/argoproj/argo-cd/v2/cmd/util"
+ "github.com/argoproj/argo-cd/v2/common"
+ argocdclient "github.com/argoproj/argo-cd/v2/pkg/apiclient"
+ "github.com/argoproj/argo-cd/v2/util/errors"
+ "github.com/argoproj/argo-cd/v2/util/settings"
+
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application"
)
const (
// YamlSeparator separates sections of a YAML file
yamlSeparator = "---\n"
-
- applicationsetNamespacesCmdParamsKey = "applicationsetcontroller.namespaces"
- applicationNamespacesCmdParamsKey = "application.namespaces"
)
var (
@@ -38,19 +38,6 @@ var (
appplicationSetResource = schema.GroupVersionResource{Group: application.Group, Version: "v1alpha1", Resource: application.ApplicationSetPlural}
)
-type argocdAdditionalNamespaces struct {
- applicationNamespaces []string
- applicationsetNamespaces []string
-}
-
-type argoCDClientsets struct {
- configMaps dynamic.ResourceInterface
- secrets dynamic.ResourceInterface
- applications dynamic.ResourceInterface
- projects dynamic.ResourceInterface
- applicationSets dynamic.ResourceInterface
-}
-
// NewAdminCommand returns a new instance of an argocd command
func NewAdminCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command {
pathOpts := clientcmd.NewDefaultPathOptions()
@@ -82,31 +69,102 @@ $ argocd admin initial-password reset
command.AddCommand(NewInitialPasswordCommand())
command.AddCommand(NewRedisInitialPasswordCommand())
- command.Flags().StringVar(&cmdutil.LogFormat, "logformat", "json", "Set the logging format. One of: json|text")
+ command.Flags().StringVar(&cmdutil.LogFormat, "logformat", "text", "Set the logging format. One of: text|json")
command.Flags().StringVar(&cmdutil.LogLevel, "loglevel", "info", "Set the logging level. One of: debug|info|warn|error")
return command
}
+type argoCDClientsets struct {
+ configMaps dynamic.ResourceInterface
+ secrets dynamic.ResourceInterface
+ applications dynamic.ResourceInterface
+ projects dynamic.ResourceInterface
+ applicationSets dynamic.ResourceInterface
+}
+
func newArgoCDClientsets(config *rest.Config, namespace string) *argoCDClientsets {
dynamicIf, err := dynamic.NewForConfig(config)
errors.CheckError(err)
-
return &argoCDClientsets{
- configMaps: dynamicIf.Resource(configMapResource).Namespace(namespace),
- secrets: dynamicIf.Resource(secretResource).Namespace(namespace),
- applications: dynamicIf.Resource(applicationsResource).Namespace(namespace),
+ configMaps: dynamicIf.Resource(configMapResource).Namespace(namespace),
+ secrets: dynamicIf.Resource(secretResource).Namespace(namespace),
+ // To support applications and applicationsets in any namespace we will watch all namespaces and filter them afterwards
+ applications: dynamicIf.Resource(applicationsResource),
projects: dynamicIf.Resource(appprojectsResource).Namespace(namespace),
- applicationSets: dynamicIf.Resource(appplicationSetResource).Namespace(namespace),
+ applicationSets: dynamicIf.Resource(appplicationSetResource),
}
}
+// 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
+ err := runtime.DefaultUnstructuredConverter.FromUnstructured(un.Object, &cm)
+ errors.CheckError(err)
+ referencedSecrets := make(map[string]bool)
+
+ // Referenced repository secrets
+ if reposRAW, ok := cm.Data["repositories"]; ok {
+ repos := make([]settings.Repository, 0)
+ err := yaml.Unmarshal([]byte(reposRAW), &repos)
+ errors.CheckError(err)
+ for _, cred := range repos {
+ if cred.PasswordSecret != nil {
+ referencedSecrets[cred.PasswordSecret.Name] = true
+ }
+ if cred.SSHPrivateKeySecret != nil {
+ referencedSecrets[cred.SSHPrivateKeySecret.Name] = true
+ }
+ if cred.UsernameSecret != nil {
+ referencedSecrets[cred.UsernameSecret.Name] = true
+ }
+ if cred.TLSClientCertDataSecret != nil {
+ referencedSecrets[cred.TLSClientCertDataSecret.Name] = true
+ }
+ if cred.TLSClientCertKeySecret != nil {
+ referencedSecrets[cred.TLSClientCertKeySecret.Name] = true
+ }
+ }
+ }
+
+ // Referenced repository credentials secrets
+ if reposRAW, ok := cm.Data["repository.credentials"]; ok {
+ creds := make([]settings.RepositoryCredentials, 0)
+ err := yaml.Unmarshal([]byte(reposRAW), &creds)
+ errors.CheckError(err)
+ for _, cred := range creds {
+ if cred.PasswordSecret != nil {
+ referencedSecrets[cred.PasswordSecret.Name] = true
+ }
+ if cred.SSHPrivateKeySecret != nil {
+ referencedSecrets[cred.SSHPrivateKeySecret.Name] = true
+ }
+ if cred.UsernameSecret != nil {
+ referencedSecrets[cred.UsernameSecret.Name] = true
+ }
+ if cred.TLSClientCertDataSecret != nil {
+ referencedSecrets[cred.TLSClientCertDataSecret.Name] = true
+ }
+ if cred.TLSClientCertKeySecret != nil {
+ referencedSecrets[cred.TLSClientCertKeySecret.Name] = true
+ }
+ }
+ }
+ return referencedSecrets
+}
+
// isArgoCDSecret returns whether or not the given secret is a part of Argo CD configuration
// (e.g. argocd-secret, repo credentials, or cluster credentials)
-func isArgoCDSecret(un unstructured.Unstructured) bool {
+func isArgoCDSecret(repoSecretRefs map[string]bool, un unstructured.Unstructured) bool {
secretName := un.GetName()
if secretName == common.ArgoCDSecretName {
return true
}
+ if repoSecretRefs != nil {
+ if _, ok := repoSecretRefs[secretName]; ok {
+ return true
+ }
+ }
if labels := un.GetLabels(); labels != nil {
if _, ok := labels[common.LabelKeySecretType]; ok {
return true
@@ -134,8 +192,8 @@ func isArgoCDConfigMap(name string) bool {
func specsEqual(left, right unstructured.Unstructured) bool {
leftAnnotation := left.GetAnnotations()
rightAnnotation := right.GetAnnotations()
- delete(leftAnnotation, corev1.LastAppliedConfigAnnotation)
- delete(rightAnnotation, corev1.LastAppliedConfigAnnotation)
+ delete(leftAnnotation, apiv1.LastAppliedConfigAnnotation)
+ delete(rightAnnotation, apiv1.LastAppliedConfigAnnotation)
if !reflect.DeepEqual(leftAnnotation, rightAnnotation) {
return false
}
@@ -169,14 +227,24 @@ func specsEqual(left, right unstructured.Unstructured) bool {
return false
}
+type argocdAdditonalNamespaces struct {
+ applicationNamespaces []string
+ applicationsetNamespaces []string
+}
+
+const (
+ applicationsetNamespacesCmdParamsKey = "applicationsetcontroller.namespaces"
+ applicationNamespacesCmdParamsKey = "application.namespaces"
+)
+
// Get additional namespaces from argocd-cmd-params
-func getAdditionalNamespaces(ctx context.Context, configMapsClient dynamic.ResourceInterface) *argocdAdditionalNamespaces {
+func getAdditionalNamespaces(ctx context.Context, argocdClientsets *argoCDClientsets) *argocdAdditonalNamespaces {
applicationNamespaces := make([]string, 0)
applicationsetNamespaces := make([]string, 0)
- un, err := configMapsClient.Get(ctx, common.ArgoCDCmdParamsConfigMapName, metav1.GetOptions{})
+ un, err := argocdClientsets.configMaps.Get(ctx, common.ArgoCDCmdParamsConfigMapName, v1.GetOptions{})
errors.CheckError(err)
- var cm corev1.ConfigMap
+ var cm apiv1.ConfigMap
err = runtime.DefaultUnstructuredConverter.FromUnstructured(un.Object, &cm)
errors.CheckError(err)
@@ -202,7 +270,7 @@ func getAdditionalNamespaces(ctx context.Context, configMapsClient dynamic.Resou
applicationsetNamespaces = namespacesListFromString(strNamespaces)
}
- return &argocdAdditionalNamespaces{
+ return &argocdAdditonalNamespaces{
applicationNamespaces: applicationNamespaces,
applicationsetNamespaces: applicationsetNamespaces,
}
diff --git a/cmd/argocd/commands/admin/admin_test.go b/cmd/argocd/commands/admin/admin_test.go
index 6b036ea292..85f59b5dee 100644
--- a/cmd/argocd/commands/admin/admin_test.go
+++ b/cmd/argocd/commands/admin/admin_test.go
@@ -1,21 +1,23 @@
package admin
import (
+ "context"
"testing"
"github.com/stretchr/testify/assert"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
+ "k8s.io/apimachinery/pkg/runtime/schema"
dynfake "k8s.io/client-go/dynamic/fake"
)
func TestGetAdditionalNamespaces(t *testing.T) {
- createArgoCDCmdCMWithKeys := func(data map[string]any) *unstructured.Unstructured {
+ createArgoCDCmdCMWithKeys := func(data map[string]interface{}) *unstructured.Unstructured {
return &unstructured.Unstructured{
- Object: map[string]any{
+ Object: map[string]interface{}{
"apiVersion": "v1",
"kind": "ConfigMap",
- "metadata": map[string]any{
+ "metadata": map[string]interface{}{
"name": "argocd-cmd-params-cm",
"namespace": "argocd",
},
@@ -25,34 +27,34 @@ func TestGetAdditionalNamespaces(t *testing.T) {
}
testCases := []struct {
- CmdParamsKeys map[string]any
- expected argocdAdditionalNamespaces
+ CmdParamsKeys map[string]interface{}
+ expected argocdAdditonalNamespaces
description string
}{
{
description: "empty configmap should return no additional namespaces",
- CmdParamsKeys: map[string]any{},
- expected: argocdAdditionalNamespaces{applicationNamespaces: []string{}, applicationsetNamespaces: []string{}},
+ CmdParamsKeys: map[string]interface{}{},
+ expected: argocdAdditonalNamespaces{applicationNamespaces: []string{}, applicationsetNamespaces: []string{}},
},
{
description: "empty strings in respective keys in cm shoud return empty namespace list",
- CmdParamsKeys: map[string]any{applicationsetNamespacesCmdParamsKey: "", applicationNamespacesCmdParamsKey: ""},
- expected: argocdAdditionalNamespaces{applicationNamespaces: []string{}, applicationsetNamespaces: []string{}},
+ CmdParamsKeys: map[string]interface{}{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]any{applicationNamespacesCmdParamsKey: "foo, bar*"},
- expected: argocdAdditionalNamespaces{applicationsetNamespaces: []string{}, applicationNamespaces: []string{"foo", "bar*"}},
+ CmdParamsKeys: map[string]interface{}{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]any{applicationsetNamespacesCmdParamsKey: "foo, bar*"},
- expected: argocdAdditionalNamespaces{applicationNamespaces: []string{}, applicationsetNamespaces: []string{"foo", "bar*"}},
+ CmdParamsKeys: map[string]interface{}{applicationsetNamespacesCmdParamsKey: "foo, bar*"},
+ expected: argocdAdditonalNamespaces{applicationNamespaces: []string{}, applicationsetNamespaces: []string{"foo", "bar*"}},
},
{
description: "whitespaces are removed for both multiple and single namespace",
- CmdParamsKeys: map[string]any{applicationNamespacesCmdParamsKey: " bar ", applicationsetNamespacesCmdParamsKey: " foo , bar* "},
- expected: argocdAdditionalNamespaces{applicationNamespaces: []string{"bar"}, applicationsetNamespaces: []string{"foo", "bar*"}},
+ CmdParamsKeys: map[string]interface{}{applicationNamespacesCmdParamsKey: " bar ", applicationsetNamespacesCmdParamsKey: " foo , bar* "},
+ expected: argocdAdditonalNamespaces{applicationNamespaces: []string{"bar"}, applicationsetNamespaces: []string{"foo", "bar*"}},
},
}
@@ -60,10 +62,14 @@ func TestGetAdditionalNamespaces(t *testing.T) {
fakeDynClient := dynfake.NewSimpleDynamicClient(runtime.NewScheme(), createArgoCDCmdCMWithKeys(c.CmdParamsKeys))
argoCDClientsets := &argoCDClientsets{
- configMaps: fakeDynClient.Resource(configMapResource).Namespace("argocd"),
+ configMaps: fakeDynClient.Resource(configMapResource).Namespace("argocd"),
+ applications: fakeDynClient.Resource(schema.GroupVersionResource{}),
+ applicationSets: fakeDynClient.Resource(schema.GroupVersionResource{}),
+ secrets: fakeDynClient.Resource(schema.GroupVersionResource{}),
+ projects: fakeDynClient.Resource(schema.GroupVersionResource{}),
}
- result := getAdditionalNamespaces(t.Context(), argoCDClientsets.configMaps)
+ result := getAdditionalNamespaces(context.TODO(), argoCDClientsets)
assert.Equal(t, c.expected, *result)
}
}
diff --git a/cmd/argocd/commands/admin/app.go b/cmd/argocd/commands/admin/app.go
index e457ad1733..d3ec7a11f0 100644
--- a/cmd/argocd/commands/admin/app.go
+++ b/cmd/argocd/commands/admin/app.go
@@ -3,18 +3,16 @@ package admin
import (
"context"
"encoding/json"
- stderrors "errors"
"fmt"
"net/http"
"os"
"sort"
"time"
- "github.com/argoproj/gitops-engine/pkg/health"
"github.com/argoproj/gitops-engine/pkg/utils/kube"
"github.com/spf13/cobra"
- corev1 "k8s.io/api/core/v1"
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+ apiv1 "k8s.io/api/core/v1"
+ v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/client-go/kubernetes"
@@ -22,28 +20,28 @@ import (
"k8s.io/client-go/tools/clientcmd"
"sigs.k8s.io/yaml"
- cmdutil "github.com/argoproj/argo-cd/v3/cmd/util"
- "github.com/argoproj/argo-cd/v3/common"
- "github.com/argoproj/argo-cd/v3/controller"
- "github.com/argoproj/argo-cd/v3/controller/cache"
- "github.com/argoproj/argo-cd/v3/controller/metrics"
- "github.com/argoproj/argo-cd/v3/controller/sharding"
- argocdclient "github.com/argoproj/argo-cd/v3/pkg/apiclient"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- appclientset "github.com/argoproj/argo-cd/v3/pkg/client/clientset/versioned"
- appinformers "github.com/argoproj/argo-cd/v3/pkg/client/informers/externalversions"
- reposerverclient "github.com/argoproj/argo-cd/v3/reposerver/apiclient"
- "github.com/argoproj/argo-cd/v3/util/argo"
- "github.com/argoproj/argo-cd/v3/util/argo/normalizers"
- cacheutil "github.com/argoproj/argo-cd/v3/util/cache"
- appstatecache "github.com/argoproj/argo-cd/v3/util/cache/appstate"
- "github.com/argoproj/argo-cd/v3/util/cli"
- "github.com/argoproj/argo-cd/v3/util/config"
- "github.com/argoproj/argo-cd/v3/util/db"
- "github.com/argoproj/argo-cd/v3/util/errors"
- utilio "github.com/argoproj/argo-cd/v3/util/io"
- kubeutil "github.com/argoproj/argo-cd/v3/util/kube"
- "github.com/argoproj/argo-cd/v3/util/settings"
+ cmdutil "github.com/argoproj/argo-cd/v2/cmd/util"
+ "github.com/argoproj/argo-cd/v2/common"
+ "github.com/argoproj/argo-cd/v2/controller"
+ "github.com/argoproj/argo-cd/v2/controller/cache"
+ "github.com/argoproj/argo-cd/v2/controller/metrics"
+ "github.com/argoproj/argo-cd/v2/controller/sharding"
+ argocdclient "github.com/argoproj/argo-cd/v2/pkg/apiclient"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+ appclientset "github.com/argoproj/argo-cd/v2/pkg/client/clientset/versioned"
+ appinformers "github.com/argoproj/argo-cd/v2/pkg/client/informers/externalversions"
+ reposerverclient "github.com/argoproj/argo-cd/v2/reposerver/apiclient"
+ "github.com/argoproj/argo-cd/v2/util/argo"
+ "github.com/argoproj/argo-cd/v2/util/argo/normalizers"
+ 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/cli"
+ "github.com/argoproj/argo-cd/v2/util/config"
+ "github.com/argoproj/argo-cd/v2/util/db"
+ "github.com/argoproj/argo-cd/v2/util/errors"
+ "github.com/argoproj/argo-cd/v2/util/io"
+ kubeutil "github.com/argoproj/argo-cd/v2/util/kube"
+ "github.com/argoproj/argo-cd/v2/util/settings"
)
func NewAppCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command {
@@ -100,7 +98,7 @@ func NewGenAppSpecCommand() *cobra.Command {
argocd admin app generate-spec nginx-ingress --repo https://charts.helm.sh/stable --helm-chart nginx-ingress --revision 1.24.3 --dest-namespace default --dest-server https://kubernetes.default.svc
# Generate declarative config for a Kustomize app
- argocd admin app generate-spec kustomize-guestbook --repo https://github.com/argoproj/argocd-example-apps.git --path kustomize-guestbook --dest-namespace default --dest-server https://kubernetes.default.svc --kustomize-image quay.io/argoprojlabs/argocd-e2e-container:0.1
+ argocd admin app generate-spec kustomize-guestbook --repo https://github.com/argoproj/argocd-example-apps.git --path kustomize-guestbook --dest-namespace default --dest-server https://kubernetes.default.svc --kustomize-image gcr.io/heptio-images/ks-guestbook-demo:0.1
# Generate declarative config for a app using a custom tool:
argocd admin app generate-spec kasane --repo https://github.com/argoproj/argocd-example-apps.git --path plugins/kasane --dest-namespace default --dest-server https://kubernetes.default.svc --config-management-plugin kasane
@@ -109,7 +107,7 @@ func NewGenAppSpecCommand() *cobra.Command {
apps, err := cmdutil.ConstructApps(fileURL, appName, labels, annotations, args, appOpts, c.Flags())
errors.CheckError(err)
if len(apps) > 1 {
- errors.CheckError(stderrors.New("failed to generate spec, more than one application is not supported"))
+ errors.CheckError(fmt.Errorf("failed to generate spec, more than one application is not supported"))
}
app := apps[0]
if app.Name == "" {
@@ -121,7 +119,7 @@ func NewGenAppSpecCommand() *cobra.Command {
}
out, closer, err := getOutWriter(inline, fileURL)
errors.CheckError(err)
- defer utilio.Close(closer)
+ defer io.Close(closer)
errors.CheckError(PrintResources(outputFormat, out, app))
},
@@ -144,7 +142,7 @@ func NewGenAppSpecCommand() *cobra.Command {
type appReconcileResult struct {
Name string `json:"name"`
- Health health.HealthStatusCode `json:"health"`
+ Health *v1alpha1.HealthStatus `json:"health"`
Sync *v1alpha1.SyncStatus `json:"sync"`
Conditions []v1alpha1.ApplicationCondition `json:"conditions"`
}
@@ -161,7 +159,7 @@ func (r *reconcileResults) getAppsMap() map[string]appReconcileResult {
return res
}
-func printLine(format string, a ...any) {
+func printLine(format string, a ...interface{}) {
_, _ = fmt.Printf(format+"\n", a...)
}
@@ -188,12 +186,12 @@ func NewDiffReconcileResults() *cobra.Command {
return command
}
-func toUnstructured(val any) (*unstructured.Unstructured, error) {
+func toUnstructured(val interface{}) (*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]any)
+ res := make(map[string]interface{})
err = json.Unmarshal(data, &res)
if err != nil {
return nil, fmt.Errorf("error while unmarhsalling data: %w", err)
@@ -286,7 +284,7 @@ func NewReconcileCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command
overrides := clientcmd.ConfigOverrides{}
repoServerName := clientOpts.RepoServerName
repoServerServiceLabelSelector := common.LabelKeyComponentRepoServer + "=" + common.LabelValueComponentRepoServer
- repoServerServices, err := kubeClientset.CoreV1().Services(namespace).List(context.Background(), metav1.ListOptions{LabelSelector: repoServerServiceLabelSelector})
+ repoServerServices, err := kubeClientset.CoreV1().Services(namespace).List(context.Background(), v1.ListOptions{LabelSelector: repoServerServiceLabelSelector})
errors.CheckError(err)
if len(repoServerServices.Items) > 0 {
if repoServerServicelabel, ok := repoServerServices.Items[0].Labels[common.LabelKeyAppName]; ok && repoServerServicelabel != "" {
@@ -339,7 +337,7 @@ func saveToFile(err error, outputFormat string, result reconcileResults, outputP
}
func getReconcileResults(ctx context.Context, appClientset appclientset.Interface, namespace string, selector string) ([]appReconcileResult, error) {
- appsList, err := appClientset.ArgoprojV1alpha1().Applications(namespace).List(ctx, metav1.ListOptions{LabelSelector: selector})
+ appsList, err := appClientset.ArgoprojV1alpha1().Applications(namespace).List(ctx, v1.ListOptions{LabelSelector: selector})
if err != nil {
return nil, fmt.Errorf("error listing namespaced apps: %w", err)
}
@@ -349,7 +347,7 @@ func getReconcileResults(ctx context.Context, appClientset appclientset.Interfac
items = append(items, appReconcileResult{
Name: app.Name,
Conditions: app.Status.Conditions,
- Health: app.Status.Health.Status,
+ Health: &app.Status.Health,
Sync: &app.Status.Sync,
})
}
@@ -373,7 +371,7 @@ func reconcileApplications(
appClientset,
1*time.Hour,
appinformers.WithNamespace(namespace),
- appinformers.WithTweakListOptions(func(_ *metav1.ListOptions) {}),
+ appinformers.WithTweakListOptions(func(options *v1.ListOptions) {}),
)
appInformer := appInformerFactory.Argoproj().V1alpha1().Applications().Informer()
@@ -381,14 +379,14 @@ func reconcileApplications(
go appInformer.Run(ctx.Done())
go projInformer.Run(ctx.Done())
if !kubecache.WaitForCacheSync(ctx.Done(), appInformer.HasSynced, projInformer.HasSynced) {
- return nil, stderrors.New("failed to sync cache")
+ return nil, fmt.Errorf("failed to sync cache")
}
appLister := appInformerFactory.Argoproj().V1alpha1().Applications().Lister()
projLister := appInformerFactory.Argoproj().V1alpha1().AppProjects().Lister()
- server, err := metrics.NewMetricsServer("", appLister, func(_ any) bool {
+ server, err := metrics.NewMetricsServer("", appLister, func(obj interface{}) bool {
return true
- }, func(_ *http.Request) error {
+ }, func(r *http.Request) error {
return nil
}, []string{}, []string{})
if err != nil {
@@ -426,7 +424,7 @@ func reconcileApplications(
ignoreNormalizerOpts,
)
- appsList, err := appClientset.ArgoprojV1alpha1().Applications(namespace).List(ctx, metav1.ListOptions{LabelSelector: selector})
+ appsList, err := appClientset.ArgoprojV1alpha1().Applications(namespace).List(ctx, v1.ListOptions{LabelSelector: selector})
if err != nil {
return nil, fmt.Errorf("error listing namespaced apps: %w", err)
}
@@ -438,19 +436,14 @@ func reconcileApplications(
var items []appReconcileResult
prevServer := ""
for _, app := range appsList.Items {
- destCluster, err := argo.GetDestinationCluster(ctx, app.Spec.Destination, argoDB)
- if err != nil {
- return nil, fmt.Errorf("error getting destination cluster: %w", err)
- }
-
- if prevServer != destCluster.Server {
+ if prevServer != app.Spec.Destination.Server {
if prevServer != "" {
- if clusterCache, err := stateCache.GetClusterCache(destCluster); err == nil {
+ if clusterCache, err := stateCache.GetClusterCache(prevServer); err == nil {
clusterCache.Invalidate()
}
}
- printLine("Reconciling apps of %s", destCluster.Server)
- prevServer = destCluster.Server
+ printLine("Reconciling apps of %s", app.Spec.Destination.Server)
+ prevServer = app.Spec.Destination.Server
}
printLine(app.Name)
@@ -479,5 +472,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(_ map[string]bool, _ corev1.ObjectReference) {}, &sharding.ClusterSharding{}, argo.NewResourceTracking())
+ return cache.NewLiveStateCache(argoDB, appInformer, settingsMgr, kubeutil.NewKubectl(), server, func(managedByApp map[string]bool, ref apiv1.ObjectReference) {}, &sharding.ClusterSharding{}, argo.NewResourceTracking())
}
diff --git a/cmd/argocd/commands/admin/app_test.go b/cmd/argocd/commands/admin/app_test.go
index 604c4faf7b..964d23ccab 100644
--- a/cmd/argocd/commands/admin/app_test.go
+++ b/cmd/argocd/commands/admin/app_test.go
@@ -1,6 +1,7 @@
package admin
import (
+ "context"
"testing"
clustermocks "github.com/argoproj/gitops-engine/pkg/cache/mocks"
@@ -15,22 +16,21 @@ import (
kubefake "k8s.io/client-go/kubernetes/fake"
"k8s.io/client-go/tools/cache"
- "github.com/argoproj/argo-cd/v3/common"
- statecache "github.com/argoproj/argo-cd/v3/controller/cache"
- cachemocks "github.com/argoproj/argo-cd/v3/controller/cache/mocks"
- "github.com/argoproj/argo-cd/v3/controller/metrics"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- appfake "github.com/argoproj/argo-cd/v3/pkg/client/clientset/versioned/fake"
- argocdclient "github.com/argoproj/argo-cd/v3/reposerver/apiclient"
- "github.com/argoproj/argo-cd/v3/reposerver/apiclient/mocks"
- "github.com/argoproj/argo-cd/v3/test"
- "github.com/argoproj/argo-cd/v3/util/argo/normalizers"
- "github.com/argoproj/argo-cd/v3/util/db"
- "github.com/argoproj/argo-cd/v3/util/settings"
+ statecache "github.com/argoproj/argo-cd/v2/controller/cache"
+ cachemocks "github.com/argoproj/argo-cd/v2/controller/cache/mocks"
+ "github.com/argoproj/argo-cd/v2/controller/metrics"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+ appfake "github.com/argoproj/argo-cd/v2/pkg/client/clientset/versioned/fake"
+ argocdclient "github.com/argoproj/argo-cd/v2/reposerver/apiclient"
+ "github.com/argoproj/argo-cd/v2/reposerver/apiclient/mocks"
+ "github.com/argoproj/argo-cd/v2/test"
+ "github.com/argoproj/argo-cd/v2/util/argo/normalizers"
+ "github.com/argoproj/argo-cd/v2/util/db"
+ "github.com/argoproj/argo-cd/v2/util/settings"
)
func TestGetReconcileResults(t *testing.T) {
- ctx := t.Context()
+ ctx := context.Background()
appClientset := appfake.NewSimpleClientset(&v1alpha1.Application{
ObjectMeta: metav1.ObjectMeta{
@@ -38,7 +38,7 @@ func TestGetReconcileResults(t *testing.T) {
Namespace: "default",
},
Status: v1alpha1.ApplicationStatus{
- Health: v1alpha1.AppHealthStatus{Status: health.HealthStatusHealthy},
+ Health: v1alpha1.HealthStatus{Status: health.HealthStatusHealthy},
Sync: v1alpha1.SyncStatus{Status: v1alpha1.SyncStatusCodeOutOfSync},
},
})
@@ -48,37 +48,24 @@ func TestGetReconcileResults(t *testing.T) {
expectedResults := []appReconcileResult{{
Name: "test",
- Health: health.HealthStatusHealthy,
+ Health: &v1alpha1.HealthStatus{Status: health.HealthStatusHealthy},
Sync: &v1alpha1.SyncStatus{Status: v1alpha1.SyncStatusCodeOutOfSync},
}}
assert.ElementsMatch(t, expectedResults, result)
}
func TestGetReconcileResults_Refresh(t *testing.T) {
- ctx := t.Context()
+ ctx := context.Background()
- argoCM := &corev1.ConfigMap{
+ cm := corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
- Name: common.ArgoCDConfigMapName,
+ Name: "argocd-cm",
Namespace: "default",
Labels: map[string]string{
"app.kubernetes.io/part-of": "argocd",
},
},
}
- argoCDSecret := &corev1.Secret{
- ObjectMeta: metav1.ObjectMeta{
- Name: common.ArgoCDSecretName,
- Namespace: "default",
- Labels: map[string]string{
- "app.kubernetes.io/part-of": "argocd",
- },
- },
- Data: map[string][]byte{
- "admin.password": nil,
- "server.secretkey": nil,
- },
- }
proj := &v1alpha1.AppProject{
ObjectMeta: metav1.ObjectMeta{
Name: "default",
@@ -104,7 +91,7 @@ func TestGetReconcileResults_Refresh(t *testing.T) {
appClientset := appfake.NewSimpleClientset(app, proj)
deployment := test.NewDeployment()
- kubeClientset := kubefake.NewClientset(deployment, argoCM, argoCDSecret)
+ kubeClientset := kubefake.NewClientset(deployment, &cm)
clusterCache := clustermocks.ClusterCache{}
clusterCache.On("IsNamespaced", mock.Anything).Return(true, nil)
clusterCache.On("GetGVKParser", mock.Anything).Return(nil)
@@ -114,7 +101,7 @@ func TestGetReconcileResults_Refresh(t *testing.T) {
}, nil)
repoServerClientset := mocks.Clientset{RepoServerServiceClient: &repoServerClient}
liveStateCache := cachemocks.LiveStateCache{}
- liveStateCache.On("GetManagedLiveObjs", mock.Anything, mock.Anything, mock.Anything).Return(map[kube.ResourceKey]*unstructured.Unstructured{
+ liveStateCache.On("GetManagedLiveObjs", mock.Anything, mock.Anything).Return(map[kube.ResourceKey]*unstructured.Unstructured{
kube.GetResourceKey(deployment): deployment,
}, nil)
liveStateCache.On("GetVersionsInfo", mock.Anything).Return("v1.2.3", nil, nil)
@@ -123,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(_ db.ArgoDB, _ cache.SharedIndexInformer, _ *settings.SettingsManager, _ *metrics.MetricsServer) statecache.LiveStateCache {
+ func(argoDB db.ArgoDB, appInformer cache.SharedIndexInformer, settingsMgr *settings.SettingsManager, server *metrics.MetricsServer) statecache.LiveStateCache {
return &liveStateCache
},
false,
@@ -132,7 +119,7 @@ func TestGetReconcileResults_Refresh(t *testing.T) {
require.NoError(t, err)
- assert.Equal(t, health.HealthStatusMissing, result[0].Health)
+ assert.Equal(t, health.HealthStatusMissing, result[0].Health.Status)
assert.Equal(t, v1alpha1.SyncStatusCodeOutOfSync, result[0].Sync.Status)
}
@@ -177,7 +164,7 @@ func TestDiffReconcileResults_DifferentApps(t *testing.T) {
app2
1,9d0
< conditions: null
-< health: ""
+< health: null
< name: app2
< sync:
< comparedTo:
@@ -188,7 +175,7 @@ app2
app3
0a1,9
> conditions: null
-> health: ""
+> health: null
> name: app3
> sync:
> comparedTo:
diff --git a/cmd/argocd/commands/admin/backup.go b/cmd/argocd/commands/admin/backup.go
index 9fb37a3097..b644b34e86 100644
--- a/cmd/argocd/commands/admin/backup.go
+++ b/cmd/argocd/commands/admin/backup.go
@@ -5,28 +5,24 @@ import (
"fmt"
"io"
"os"
- "strings"
- "time"
"github.com/argoproj/gitops-engine/pkg/utils/kube"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
- apierrors "k8s.io/apimachinery/pkg/api/errors"
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+ apierr "k8s.io/apimachinery/pkg/api/errors"
+ v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/tools/clientcmd"
-
- "k8s.io/client-go/util/retry"
"sigs.k8s.io/yaml"
- "github.com/argoproj/argo-cd/v3/cmd/argocd/commands/utils"
- "github.com/argoproj/argo-cd/v3/common"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application"
- "github.com/argoproj/argo-cd/v3/util/cli"
- "github.com/argoproj/argo-cd/v3/util/errors"
- "github.com/argoproj/argo-cd/v3/util/localconfig"
- secutil "github.com/argoproj/argo-cd/v3/util/security"
+ "github.com/argoproj/argo-cd/v2/cmd/argocd/commands/utils"
+ "github.com/argoproj/argo-cd/v2/common"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application"
+ "github.com/argoproj/argo-cd/v2/util/cli"
+ "github.com/argoproj/argo-cd/v2/util/errors"
+ "github.com/argoproj/argo-cd/v2/util/localconfig"
+ secutil "github.com/argoproj/argo-cd/v2/util/security"
)
// NewExportCommand defines a new command for exporting Kubernetes and Argo CD resources.
@@ -40,16 +36,13 @@ 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, _ []string) {
+ Run: func(c *cobra.Command, args []string) {
ctx := c.Context()
config, err := clientConfig.ClientConfig()
errors.CheckError(err)
- client, err := dynamic.NewForConfig(config)
- errors.CheckError(err)
namespace, _, err := clientConfig.Namespace()
errors.CheckError(err)
- acdClients := newArgoCDClientsets(config, namespace)
var writer io.Writer
if out == "-" {
@@ -67,51 +60,44 @@ func NewExportCommand() *cobra.Command {
}()
}
- if len(applicationNamespaces) == 0 || len(applicationsetNamespaces) == 0 {
- defaultNs := getAdditionalNamespaces(ctx, acdClients.configMaps)
- if len(applicationNamespaces) == 0 {
- applicationNamespaces = defaultNs.applicationNamespaces
- }
- if len(applicationsetNamespaces) == 0 {
- applicationsetNamespaces = defaultNs.applicationsetNamespaces
- }
- }
- // To support applications and applicationsets in any namespace, we must list ALL namespaces and filter them afterwards
- if len(applicationNamespaces) > 0 {
- acdClients.applications = client.Resource(applicationsResource)
- }
- if len(applicationsetNamespaces) > 0 {
- acdClients.applicationSets = client.Resource(appplicationSetResource)
- }
-
- acdConfigMap, err := acdClients.configMaps.Get(ctx, common.ArgoCDConfigMapName, metav1.GetOptions{})
+ acdClients := newArgoCDClientsets(config, namespace)
+ acdConfigMap, err := acdClients.configMaps.Get(ctx, common.ArgoCDConfigMapName, v1.GetOptions{})
errors.CheckError(err)
export(writer, *acdConfigMap, namespace)
- acdRBACConfigMap, err := acdClients.configMaps.Get(ctx, common.ArgoCDRBACConfigMapName, metav1.GetOptions{})
+ acdRBACConfigMap, err := acdClients.configMaps.Get(ctx, common.ArgoCDRBACConfigMapName, v1.GetOptions{})
errors.CheckError(err)
export(writer, *acdRBACConfigMap, namespace)
- acdKnownHostsConfigMap, err := acdClients.configMaps.Get(ctx, common.ArgoCDKnownHostsConfigMapName, metav1.GetOptions{})
+ acdKnownHostsConfigMap, err := acdClients.configMaps.Get(ctx, common.ArgoCDKnownHostsConfigMapName, v1.GetOptions{})
errors.CheckError(err)
export(writer, *acdKnownHostsConfigMap, namespace)
- acdTLSCertsConfigMap, err := acdClients.configMaps.Get(ctx, common.ArgoCDTLSCertsConfigMapName, metav1.GetOptions{})
+ acdTLSCertsConfigMap, err := acdClients.configMaps.Get(ctx, common.ArgoCDTLSCertsConfigMapName, v1.GetOptions{})
errors.CheckError(err)
export(writer, *acdTLSCertsConfigMap, namespace)
- secrets, err := acdClients.secrets.List(ctx, metav1.ListOptions{})
+ referencedSecrets := getReferencedSecrets(*acdConfigMap)
+ secrets, err := acdClients.secrets.List(ctx, v1.ListOptions{})
errors.CheckError(err)
for _, secret := range secrets.Items {
- if isArgoCDSecret(secret) {
+ if isArgoCDSecret(referencedSecrets, secret) {
export(writer, secret, namespace)
}
}
-
- projects, err := acdClients.projects.List(ctx, metav1.ListOptions{})
+ projects, err := acdClients.projects.List(ctx, v1.ListOptions{})
errors.CheckError(err)
for _, proj := range projects.Items {
export(writer, proj, namespace)
}
- applications, err := acdClients.applications.List(ctx, metav1.ListOptions{})
+ additionalNamespaces := getAdditionalNamespaces(ctx, acdClients)
+
+ if len(applicationNamespaces) == 0 {
+ applicationNamespaces = additionalNamespaces.applicationNamespaces
+ }
+ if len(applicationsetNamespaces) == 0 {
+ applicationsetNamespaces = additionalNamespaces.applicationsetNamespaces
+ }
+
+ applications, err := acdClients.applications.List(ctx, v1.ListOptions{})
errors.CheckError(err)
for _, app := range applications.Items {
// Export application only if it is in one of the enabled namespaces
@@ -119,9 +105,9 @@ func NewExportCommand() *cobra.Command {
export(writer, app, namespace)
}
}
- applicationSets, err := acdClients.applicationSets.List(ctx, metav1.ListOptions{})
- if err != nil && !apierrors.IsNotFound(err) {
- if apierrors.IsForbidden(err) {
+ applicationSets, err := acdClients.applicationSets.List(ctx, v1.ListOptions{})
+ if err != nil && !apierr.IsNotFound(err) {
+ if apierr.IsForbidden(err) {
log.Warn(err)
} else {
errors.CheckError(err)
@@ -139,18 +125,8 @@ func NewExportCommand() *cobra.Command {
clientConfig = cli.AddKubectlFlagsToCmd(&command)
command.Flags().StringVarP(&out, "out", "o", "-", "Output to the specified file instead of stdout")
- command.Flags().StringSliceVarP(&applicationNamespaces, "application-namespaces", "", []string{}, fmt.Sprintf("Comma-separated list of namespace globs to export applications from, in addition to the control plane namespace (Argo CD namespace). "+
- "By default, all applications from the control plane namespace are always exported. "+
- "If this flag is provided, applications from the specified namespaces are exported along with the control plane namespace. "+
- "If not specified, the value from '%s' in %s is used (if defined in the ConfigMap). "+
- "If the ConfigMap value is not set, only applications from the control plane namespace are exported.",
- applicationNamespacesCmdParamsKey, common.ArgoCDCmdParamsConfigMapName))
- command.Flags().StringSliceVarP(&applicationsetNamespaces, "applicationset-namespaces", "", []string{}, fmt.Sprintf("Comma-separated list of namespace globs to export ApplicationSets from, in addition to the control plane namespace (Argo CD namespace). "+
- "By default, all ApplicationSets from the control plane namespace are always exported. "+
- "If this flag is provided, ApplicationSets from the specified namespaces are exported along with the control plane namespace. "+
- "If not specified, the value from '%s' in %s is used (if defined in the ConfigMap). "+
- "If the ConfigMap value is not set, only ApplicationSets from the control plane namespace are exported.",
- applicationsetNamespacesCmdParamsKey, common.ArgoCDCmdParamsConfigMapName))
+ command.Flags().StringSliceVarP(&applicationNamespaces, "application-namespaces", "", []string{}, fmt.Sprintf("Comma separated list of namespace globs to export applications from. If not provided value from '%s' in %s will be used,if it's not defined only applications from Argo CD namespace will be exported", applicationNamespacesCmdParamsKey, common.ArgoCDCmdParamsConfigMapName))
+ command.Flags().StringSliceVarP(&applicationsetNamespaces, "applicationset-namespaces", "", []string{}, fmt.Sprintf("Comma separated list of namespace globs to export applicationsets from. If not provided value from '%s' in %s will be used,if it's not defined only applicationsets from Argo CD namespace will be exported", applicationsetNamespacesCmdParamsKey, common.ArgoCDCmdParamsConfigMapName))
return &command
}
@@ -163,9 +139,7 @@ func NewImportCommand() *cobra.Command {
verbose bool
stopOperation bool
ignoreTracking bool
- overrideOnConflict bool
promptsEnabled bool
- skipResourcesWithLabel string
applicationNamespaces []string
applicationsetNamespaces []string
)
@@ -188,8 +162,7 @@ func NewImportCommand() *cobra.Command {
acdClients := newArgoCDClientsets(config, namespace)
client, err := dynamic.NewForConfig(config)
errors.CheckError(err)
- fmt.Printf("import process started %s\n", namespace)
- tt := time.Now()
+
var input []byte
if in := args[0]; in == "-" {
input, err = io.ReadAll(os.Stdin)
@@ -202,57 +175,54 @@ func NewImportCommand() *cobra.Command {
dryRunMsg = " (dry run)"
}
- if len(applicationNamespaces) == 0 || len(applicationsetNamespaces) == 0 {
- defaultNs := getAdditionalNamespaces(ctx, acdClients.configMaps)
- if len(applicationNamespaces) == 0 {
- applicationNamespaces = defaultNs.applicationNamespaces
- }
- if len(applicationsetNamespaces) == 0 {
- applicationsetNamespaces = defaultNs.applicationsetNamespaces
- }
+ additionalNamespaces := getAdditionalNamespaces(ctx, acdClients)
+
+ if len(applicationNamespaces) == 0 {
+ applicationNamespaces = additionalNamespaces.applicationNamespaces
}
- // To support applications and applicationsets in any namespace, we must list ALL namespaces and filter them afterwards
- if len(applicationNamespaces) > 0 {
- acdClients.applications = client.Resource(applicationsResource)
- }
- if len(applicationsetNamespaces) > 0 {
- acdClients.applicationSets = client.Resource(appplicationSetResource)
+ if len(applicationsetNamespaces) == 0 {
+ applicationsetNamespaces = additionalNamespaces.applicationsetNamespaces
}
- // pruneObjects tracks live objects, and it's current resource version. any remaining
+ // pruneObjects tracks live objects and it's current resource version. any remaining
// items in this map indicates the resource should be pruned since it no longer appears
// in the backup
pruneObjects := make(map[kube.ResourceKey]unstructured.Unstructured)
- configMaps, err := acdClients.configMaps.List(ctx, metav1.ListOptions{})
-
+ configMaps, err := acdClients.configMaps.List(ctx, v1.ListOptions{})
errors.CheckError(err)
+ // referencedSecrets holds any secrets referenced in the argocd-cm configmap. These
+ // secrets need to be imported too
+ var referencedSecrets map[string]bool
for _, cm := range configMaps.Items {
if isArgoCDConfigMap(cm.GetName()) {
pruneObjects[kube.ResourceKey{Group: "", Kind: "ConfigMap", Name: cm.GetName(), Namespace: cm.GetNamespace()}] = cm
}
+ if cm.GetName() == common.ArgoCDConfigMapName {
+ referencedSecrets = getReferencedSecrets(cm)
+ }
}
- secrets, err := acdClients.secrets.List(ctx, metav1.ListOptions{})
+ secrets, err := acdClients.secrets.List(ctx, v1.ListOptions{})
errors.CheckError(err)
for _, secret := range secrets.Items {
- if isArgoCDSecret(secret) {
+ if isArgoCDSecret(referencedSecrets, secret) {
pruneObjects[kube.ResourceKey{Group: "", Kind: "Secret", Name: secret.GetName(), Namespace: secret.GetNamespace()}] = secret
}
}
- applications, err := acdClients.applications.List(ctx, metav1.ListOptions{})
+ applications, err := acdClients.applications.List(ctx, v1.ListOptions{})
errors.CheckError(err)
for _, app := range applications.Items {
if secutil.IsNamespaceEnabled(app.GetNamespace(), namespace, applicationNamespaces) {
pruneObjects[kube.ResourceKey{Group: application.Group, Kind: application.ApplicationKind, Name: app.GetName(), Namespace: app.GetNamespace()}] = app
}
}
- projects, err := acdClients.projects.List(ctx, metav1.ListOptions{})
+ projects, err := acdClients.projects.List(ctx, v1.ListOptions{})
errors.CheckError(err)
for _, proj := range projects.Items {
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 apierrors.IsForbidden(err) || apierrors.IsNotFound(err) {
+ applicationSets, err := acdClients.applicationSets.List(ctx, v1.ListOptions{})
+ if apierr.IsForbidden(err) || apierr.IsNotFound(err) {
log.Warnf("argoproj.io/ApplicationSet: %v\n", err)
} else {
errors.CheckError(err)
@@ -264,9 +234,9 @@ func NewImportCommand() *cobra.Command {
}
}
}
+
// Create or replace existing object
backupObjects, err := kube.SplitYAML(input)
-
errors.CheckError(err)
for _, bakObj := range backupObjects {
gvk := bakObj.GroupVersionKind()
@@ -277,13 +247,6 @@ func NewImportCommand() *cobra.Command {
key := kube.ResourceKey{Group: gvk.Group, Kind: gvk.Kind, Name: bakObj.GetName(), Namespace: bakObj.GetNamespace()}
liveObj, exists := pruneObjects[key]
delete(pruneObjects, key)
-
- // If the resource in backup matches the skip label, do not import it
- if isSkipLabelMatches(bakObj, skipResourcesWithLabel) {
- fmt.Printf("Skipping %s/%s %s in namespace %s\n", bakObj.GroupVersionKind().Group, bakObj.GroupVersionKind().Kind, bakObj.GetName(), bakObj.GetNamespace())
- continue
- }
-
var dynClient dynamic.ResourceInterface
switch bakObj.GetKind() {
case "Secret":
@@ -293,17 +256,17 @@ func NewImportCommand() *cobra.Command {
case application.AppProjectKind:
dynClient = client.Resource(appprojectsResource).Namespace(bakObj.GetNamespace())
case application.ApplicationKind:
+ dynClient = client.Resource(applicationsResource).Namespace(bakObj.GetNamespace())
// If application is not in one of the allowed namespaces do not import it
if !secutil.IsNamespaceEnabled(bakObj.GetNamespace(), namespace, applicationNamespaces) {
continue
}
- dynClient = client.Resource(applicationsResource).Namespace(bakObj.GetNamespace())
case application.ApplicationSetKind:
+ dynClient = client.Resource(appplicationSetResource).Namespace(bakObj.GetNamespace())
// If applicationset is not in one of the allowed namespaces do not import it
if !secutil.IsNamespaceEnabled(bakObj.GetNamespace(), namespace, applicationsetNamespaces) {
continue
}
- dynClient = client.Resource(appplicationSetResource).Namespace(bakObj.GetNamespace())
}
// If there is a live object, remove the tracking annotations/label that might conflict
@@ -312,12 +275,11 @@ func NewImportCommand() *cobra.Command {
updateTracking(bakObj, &liveObj)
}
- switch {
- case !exists:
+ if !exists {
isForbidden := false
if !dryRun {
- _, err = dynClient.Create(ctx, bakObj, metav1.CreateOptions{})
- if apierrors.IsForbidden(err) || apierrors.IsNotFound(err) {
+ _, err = dynClient.Create(ctx, bakObj, v1.CreateOptions{})
+ if apierr.IsForbidden(err) || apierr.IsNotFound(err) {
isForbidden = true
log.Warnf("%s/%s %s: %v", gvk.Group, gvk.Kind, bakObj.GetName(), err)
} else {
@@ -327,31 +289,16 @@ func NewImportCommand() *cobra.Command {
if !isForbidden {
fmt.Printf("%s/%s %s in namespace %s created%s\n", gvk.Group, gvk.Kind, bakObj.GetName(), bakObj.GetNamespace(), dryRunMsg)
}
- case specsEqual(*bakObj, liveObj) && checkAppHasNoNeedToStopOperation(liveObj, stopOperation):
+ } else if specsEqual(*bakObj, liveObj) && checkAppHasNoNeedToStopOperation(liveObj, stopOperation) {
if verbose {
fmt.Printf("%s/%s %s unchanged%s\n", gvk.Group, gvk.Kind, bakObj.GetName(), dryRunMsg)
}
- default:
+ } else {
isForbidden := false
if !dryRun {
newLive := updateLive(bakObj, &liveObj, stopOperation)
- _, err = dynClient.Update(ctx, newLive, metav1.UpdateOptions{})
- if apierrors.IsConflict(err) {
- fmt.Printf("Failed to update %s/%s %s in namespace %s: %v\n", gvk.Group, gvk.Kind, bakObj.GetName(), bakObj.GetNamespace(), err)
- if overrideOnConflict {
- err = retry.RetryOnConflict(retry.DefaultRetry, func() error {
- fmt.Printf("Resource conflict: retrying update for Group: %s, Kind: %s, Name: %s, Namespace: %s\n", gvk.Group, gvk.Kind, bakObj.GetName(), bakObj.GetNamespace())
- liveObj, getErr := dynClient.Get(ctx, newLive.GetName(), metav1.GetOptions{})
- if getErr != nil {
- errors.CheckError(getErr)
- }
- newLive.SetResourceVersion(liveObj.GetResourceVersion())
- _, err = dynClient.Update(ctx, newLive, metav1.UpdateOptions{})
- return err
- })
- }
- }
- if apierrors.IsForbidden(err) || apierrors.IsNotFound(err) {
+ _, err = dynClient.Update(ctx, newLive, v1.UpdateOptions{})
+ if apierr.IsForbidden(err) || apierr.IsNotFound(err) {
isForbidden = true
log.Warnf("%s/%s %s: %v", gvk.Group, gvk.Kind, bakObj.GetName(), err)
} else {
@@ -368,12 +315,6 @@ func NewImportCommand() *cobra.Command {
// Delete objects not in backup
for key, liveObj := range pruneObjects {
- // If a live resource has a label to skip the import, it should never be pruned
- if isSkipLabelMatches(&liveObj, skipResourcesWithLabel) {
- fmt.Printf("Skipping pruning of %s/%s %s in namespace %s\n", key.Group, key.Kind, liveObj.GetName(), liveObj.GetNamespace())
- continue
- }
-
if prune {
var dynClient dynamic.ResourceInterface
switch key.Kind {
@@ -387,8 +328,8 @@ func NewImportCommand() *cobra.Command {
if finalizers := liveObj.GetFinalizers(); len(finalizers) > 0 {
newLive := liveObj.DeepCopy()
newLive.SetFinalizers(nil)
- _, err = dynClient.Update(ctx, newLive, metav1.UpdateOptions{})
- if err != nil && !apierrors.IsNotFound(err) {
+ _, err = dynClient.Update(ctx, newLive, v1.UpdateOptions{})
+ if err != nil && !apierr.IsNotFound(err) {
errors.CheckError(err)
}
}
@@ -403,8 +344,8 @@ func NewImportCommand() *cobra.Command {
if !dryRun {
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 apierrors.IsForbidden(err) || apierrors.IsNotFound(err) {
+ err = dynClient.Delete(ctx, key.Name, v1.DeleteOptions{})
+ if apierr.IsForbidden(err) || apierr.IsNotFound(err) {
isForbidden = true
log.Warnf("%s/%s %s: %v\n", key.Group, key.Kind, key.Name, err)
} else {
@@ -421,8 +362,6 @@ func NewImportCommand() *cobra.Command {
fmt.Printf("%s/%s %s needs pruning\n", key.Group, key.Kind, key.Name)
}
}
- duration := time.Since(tt)
- fmt.Printf("Import process completed successfully in namespace %s at %s, duration: %s\n", namespace, time.Now().Format(time.RFC3339), duration)
},
}
@@ -430,13 +369,12 @@ func NewImportCommand() *cobra.Command {
command.Flags().BoolVar(&dryRun, "dry-run", false, "Print what will be performed")
command.Flags().BoolVar(&prune, "prune", false, "Prune secrets, applications and projects which do not appear in the backup")
command.Flags().BoolVar(&ignoreTracking, "ignore-tracking", false, "Do not update the tracking annotation if the resource is already tracked")
- command.Flags().BoolVar(&overrideOnConflict, "override-on-conflict", false, "Override the resource on conflict when updating resources")
command.Flags().BoolVar(&verbose, "verbose", false, "Verbose output (versus only changed output)")
command.Flags().BoolVar(&stopOperation, "stop-operation", false, "Stop any existing operations")
- command.Flags().StringVarP(&skipResourcesWithLabel, "skip-resources-with-label", "", "", "Skip importing resources based on the label e.g. '--skip-resources-with-label my-label/example.io=true'")
- command.Flags().StringSliceVarP(&applicationNamespaces, "application-namespaces", "", []string{}, fmt.Sprintf("Comma separated list of namespace globs to which import of applications is allowed. If not provided, value from '%s' in %s will be used. If it's not defined, only applications without an explicit namespace will be imported to the Argo CD namespace", applicationNamespacesCmdParamsKey, common.ArgoCDCmdParamsConfigMapName))
- command.Flags().StringSliceVarP(&applicationsetNamespaces, "applicationset-namespaces", "", []string{}, fmt.Sprintf("Comma separated list of namespace globs which import of applicationsets is allowed. If not provided, value from '%s' in %s will be used. If it's not defined, only applicationsets without an explicit namespace will be imported to the Argo CD namespace", applicationsetNamespacesCmdParamsKey, common.ArgoCDCmdParamsConfigMapName))
+ command.Flags().StringSliceVarP(&applicationNamespaces, "application-namespaces", "", []string{}, fmt.Sprintf("Comma separated list of namespace globs to which import of applications is allowed. If not provided value from '%s' in %s will be used,if it's not defined only applications without an explicit namespace will be imported to the Argo CD namespace", applicationNamespacesCmdParamsKey, common.ArgoCDCmdParamsConfigMapName))
+ command.Flags().StringSliceVarP(&applicationsetNamespaces, "applicationset-namespaces", "", []string{}, fmt.Sprintf("Comma separated list of namespace globs which import of applicationsets is allowed. If not provided value from '%s' in %s will be used,if it's not defined only applicationsets without an explicit namespace will be imported to the Argo CD namespace", applicationsetNamespacesCmdParamsKey, common.ArgoCDCmdParamsConfigMapName))
command.PersistentFlags().BoolVar(&promptsEnabled, "prompts-enabled", localconfig.GetPromptsEnabled(true), "Force optional interactive prompts to be enabled or disabled, overriding local configuration. If not specified, the local configuration value will be used, which is false by default.")
+
return &command
}
@@ -445,7 +383,8 @@ func checkAppHasNoNeedToStopOperation(liveObj unstructured.Unstructured, stopOpe
if !stopOperation {
return true
}
- if liveObj.GetKind() == application.ApplicationKind {
+ switch liveObj.GetKind() {
+ case application.ApplicationKind:
return liveObj.Object["operation"] == nil
}
return true
@@ -468,7 +407,6 @@ func export(w io.Writer, un unstructured.Unstructured, argocdNamespace string) {
un.SetLabels(labels)
un.SetAnnotations(annotations)
if namespace != argocdNamespace {
- // Explicitly add the namespace for appset and apps in any namespace
un.SetNamespace(namespace)
}
data, err := yaml.Marshal(un.Object)
@@ -534,19 +472,3 @@ func updateTracking(bak, live *unstructured.Unstructured) {
}
}
}
-
-// isSkipLabelMatches return if the resource should be skipped based on the labels
-func isSkipLabelMatches(obj *unstructured.Unstructured, skipResourcesWithLabel string) bool {
- if skipResourcesWithLabel == "" {
- return false
- }
- parts := strings.SplitN(skipResourcesWithLabel, "=", 2)
- if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
- return false
- }
- key, value := parts[0], parts[1]
- if val, ok := obj.GetLabels()[key]; ok && val == value {
- return true
- }
- return false
-}
diff --git a/cmd/argocd/commands/admin/backup_test.go b/cmd/argocd/commands/admin/backup_test.go
index d1f638711b..b4fd07ad04 100644
--- a/cmd/argocd/commands/admin/backup_test.go
+++ b/cmd/argocd/commands/admin/backup_test.go
@@ -1,23 +1,19 @@
package admin
import (
- "bytes"
"testing"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- "github.com/argoproj/argo-cd/v3/util/security"
-
"github.com/argoproj/gitops-engine/pkg/utils/kube"
"github.com/stretchr/testify/assert"
- 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"
- "github.com/argoproj/argo-cd/v3/common"
+ "github.com/argoproj/argo-cd/v2/common"
)
func newBackupObject(trackingValue string, trackingLabel bool, trackingAnnotation bool) *unstructured.Unstructured {
- cm := corev1.ConfigMap{
+ cm := v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: "my-configmap",
Namespace: "namespace",
@@ -39,329 +35,6 @@ func newBackupObject(trackingValue string, trackingLabel bool, trackingAnnotatio
return kube.MustToUnstructured(&cm)
}
-func newConfigmapObject() *unstructured.Unstructured {
- cm := corev1.ConfigMap{
- ObjectMeta: metav1.ObjectMeta{
- Name: common.ArgoCDConfigMapName,
- Namespace: "argocd",
- Labels: map[string]string{
- "app.kubernetes.io/part-of": "argocd",
- },
- },
- }
-
- return kube.MustToUnstructured(&cm)
-}
-
-func newSecretsObject() *unstructured.Unstructured {
- secret := corev1.Secret{
- ObjectMeta: metav1.ObjectMeta{
- Name: common.ArgoCDSecretName,
- Namespace: "default",
- Labels: map[string]string{
- "app.kubernetes.io/part-of": "argocd",
- },
- },
- Data: map[string][]byte{
- "admin.password": nil,
- "server.secretkey": nil,
- },
- }
-
- return kube.MustToUnstructured(&secret)
-}
-
-func newAppProject() *unstructured.Unstructured {
- appProject := v1alpha1.AppProject{
- ObjectMeta: metav1.ObjectMeta{
- Name: "default",
- Namespace: "argocd",
- },
- Spec: v1alpha1.AppProjectSpec{
- Destinations: []v1alpha1.ApplicationDestination{
- {
- Namespace: "*",
- Server: "*",
- },
- },
- ClusterResourceWhitelist: []metav1.GroupKind{
- {
- Group: "*",
- Kind: "*",
- },
- },
- SourceRepos: []string{"*"},
- },
- }
-
- return kube.MustToUnstructured(&appProject)
-}
-
-func newApplication(namespace string) *unstructured.Unstructured {
- app := v1alpha1.Application{
- TypeMeta: metav1.TypeMeta{
- Kind: "Application",
- },
- ObjectMeta: metav1.ObjectMeta{
- Name: "test",
- Namespace: namespace,
- },
- Spec: v1alpha1.ApplicationSpec{
- Source: &v1alpha1.ApplicationSource{},
- Project: "default",
- Destination: v1alpha1.ApplicationDestination{
- Server: v1alpha1.KubernetesInternalAPIServerAddr,
- Namespace: "default",
- },
- },
- }
-
- return kube.MustToUnstructured(&app)
-}
-
-func newApplicationSet(namespace string) *unstructured.Unstructured {
- appSet := v1alpha1.ApplicationSet{
- TypeMeta: metav1.TypeMeta{
- Kind: "ApplicationSet",
- },
- ObjectMeta: metav1.ObjectMeta{
- Name: "test-appset",
- Namespace: namespace,
- },
- Spec: v1alpha1.ApplicationSetSpec{
- Generators: []v1alpha1.ApplicationSetGenerator{
- {
- Git: &v1alpha1.GitGenerator{
- RepoURL: "https://github.com/org/repo",
- },
- },
- },
- },
- }
-
- return kube.MustToUnstructured(&appSet)
-}
-
-// Test_exportResources tests for the resources exported when using the `argocd admin export` command
-func Test_exportResources(t *testing.T) {
- tests := []struct {
- name string
- object *unstructured.Unstructured
- namespace string
- enabledNamespaces []string
- expectedFileContent string
- expectExport bool
- }{
- {
- name: "ConfigMap should be in the exported manifest",
- object: newConfigmapObject(),
- expectExport: true,
- expectedFileContent: `apiVersion: ""
-kind: ""
-metadata:
- labels:
- app.kubernetes.io/part-of: argocd
- name: argocd-cm
----
-`,
- },
- {
- name: "Secret should be in the exported manifest",
- object: newSecretsObject(),
- expectExport: true,
- expectedFileContent: `apiVersion: ""
-data:
- admin.password: null
- server.secretkey: null
-kind: ""
-metadata:
- labels:
- app.kubernetes.io/part-of: argocd
- name: argocd-secret
- namespace: default
----
-`,
- },
- {
- name: "App Project should be in the exported manifest",
- object: newAppProject(),
- expectExport: true,
- expectedFileContent: `apiVersion: ""
-kind: ""
-metadata:
- name: default
-spec:
- clusterResourceWhitelist:
- - group: '*'
- kind: '*'
- destinations:
- - namespace: '*'
- server: '*'
- sourceRepos:
- - '*'
-status: {}
----
-`,
- },
- {
- name: "Application should be in the exported manifest when created in the default 'argocd' namespace",
- object: newApplication("argocd"),
- namespace: "argocd",
- expectExport: true,
- expectedFileContent: `apiVersion: ""
-kind: Application
-metadata:
- name: test
-spec:
- destination:
- namespace: default
- server: https://kubernetes.default.svc
- project: default
- source:
- repoURL: ""
-status:
- health: {}
- sourceHydrator: {}
- summary: {}
- sync:
- comparedTo:
- destination: {}
- source:
- repoURL: ""
- status: ""
----
-`,
- },
- {
- name: "Application should be in the exported manifest when created in the enabled namespaces",
- object: newApplication("dev"),
- namespace: "dev",
- enabledNamespaces: []string{"dev", "prod"},
- expectExport: true,
- expectedFileContent: `apiVersion: ""
-kind: Application
-metadata:
- name: test
- namespace: dev
-spec:
- destination:
- namespace: default
- server: https://kubernetes.default.svc
- project: default
- source:
- repoURL: ""
-status:
- health: {}
- sourceHydrator: {}
- summary: {}
- sync:
- comparedTo:
- destination: {}
- source:
- repoURL: ""
- status: ""
----
-`,
- },
- {
- name: "Application should not be in the exported manifest when it's neither created in the default argod namespace nor in enabled namespace",
- object: newApplication("staging"),
- namespace: "staging",
- enabledNamespaces: []string{"dev", "prod"},
- expectExport: false,
- expectedFileContent: ``,
- },
- {
- name: "ApplicationSet should be in the exported manifest when created in the default 'argocd' namespace",
- object: newApplicationSet("argocd"),
- namespace: "argocd",
- expectExport: true,
- expectedFileContent: `apiVersion: ""
-kind: ApplicationSet
-metadata:
- name: test-appset
-spec:
- generators:
- - git:
- repoURL: https://github.com/org/repo
- revision: ""
- template:
- metadata: {}
- spec:
- destination: {}
- project: ""
- template:
- metadata: {}
- spec:
- destination: {}
- project: ""
-status: {}
----
-`,
- },
- {
- name: "ApplicationSet should be in the exported manifest when created in the enabled namespaces",
- object: newApplicationSet("dev"),
- namespace: "dev",
- enabledNamespaces: []string{"dev", "prod"},
- expectExport: true,
- expectedFileContent: `apiVersion: ""
-kind: ApplicationSet
-metadata:
- name: test-appset
- namespace: dev
-spec:
- generators:
- - git:
- repoURL: https://github.com/org/repo
- revision: ""
- template:
- metadata: {}
- spec:
- destination: {}
- project: ""
- template:
- metadata: {}
- spec:
- destination: {}
- project: ""
-status: {}
----
-`,
- },
- {
- name: "ApplicationSet should not be in the exported manifest when neither created in the default 'argocd' namespace nor in enabled namespaces",
- object: newApplicationSet("staging"),
- namespace: "staging",
- enabledNamespaces: []string{"dev", "prod"},
- expectExport: false,
- expectedFileContent: ``,
- },
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- var buf bytes.Buffer
-
- kind := tt.object.GetKind()
- if kind == "Application" || kind == "ApplicationSet" {
- if security.IsNamespaceEnabled(tt.namespace, "argocd", tt.enabledNamespaces) {
- export(&buf, *tt.object, ArgoCDNamespace)
- }
- } else {
- export(&buf, *tt.object, ArgoCDNamespace)
- }
-
- content := buf.String()
- if tt.expectExport {
- assert.Equal(t, tt.expectedFileContent, content)
- } else {
- assert.Empty(t, content)
- }
- })
- }
-}
-
func Test_updateTracking(t *testing.T) {
type args struct {
bak *unstructured.Unstructured
@@ -412,76 +85,3 @@ func Test_updateTracking(t *testing.T) {
})
}
}
-
-func TestIsSkipLabelMatches(t *testing.T) {
- tests := []struct {
- name string
- obj *unstructured.Unstructured
- skipLabels string
- expected bool
- }{
- {
- name: "Label matches",
- obj: &unstructured.Unstructured{
- Object: map[string]any{
- "metadata": map[string]any{
- "labels": map[string]any{
- "test-label": "value",
- },
- },
- },
- },
- skipLabels: "test-label=value",
- expected: true,
- },
- {
- name: "Label does not match",
- obj: &unstructured.Unstructured{
- Object: map[string]any{
- "metadata": map[string]any{
- "labels": map[string]any{
- "different-label": "value",
- },
- },
- },
- },
- skipLabels: "test-label=value",
- expected: false,
- },
- {
- name: "Empty skip labels",
- obj: &unstructured.Unstructured{
- Object: map[string]any{
- "metadata": map[string]any{
- "labels": map[string]any{
- "test-label": "value",
- },
- },
- },
- },
- skipLabels: "",
- expected: false,
- },
- {
- name: "No labels value",
- obj: &unstructured.Unstructured{
- Object: map[string]any{
- "metadata": map[string]any{
- "labels": map[string]any{
- "test-label": "value",
- "another-label": "value2",
- },
- },
- },
- },
- skipLabels: "test-label",
- expected: false,
- },
- }
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- result := isSkipLabelMatches(tt.obj, tt.skipLabels)
- assert.Equal(t, tt.expected, result)
- })
- }
-}
diff --git a/cmd/argocd/commands/admin/cluster.go b/cmd/argocd/commands/admin/cluster.go
index a0ce6910be..04d9a148b2 100644
--- a/cmd/argocd/commands/admin/cluster.go
+++ b/cmd/argocd/commands/admin/cluster.go
@@ -14,30 +14,30 @@ import (
"github.com/redis/go-redis/v9"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+ v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/kubernetes/fake"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/utils/ptr"
- cmdutil "github.com/argoproj/argo-cd/v3/cmd/util"
- "github.com/argoproj/argo-cd/v3/common"
- "github.com/argoproj/argo-cd/v3/controller/sharding"
- argocdclient "github.com/argoproj/argo-cd/v3/pkg/apiclient"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- "github.com/argoproj/argo-cd/v3/pkg/client/clientset/versioned"
- "github.com/argoproj/argo-cd/v3/util/argo"
- cacheutil "github.com/argoproj/argo-cd/v3/util/cache"
- appstatecache "github.com/argoproj/argo-cd/v3/util/cache/appstate"
- "github.com/argoproj/argo-cd/v3/util/cli"
- "github.com/argoproj/argo-cd/v3/util/clusterauth"
- "github.com/argoproj/argo-cd/v3/util/db"
- "github.com/argoproj/argo-cd/v3/util/errors"
- "github.com/argoproj/argo-cd/v3/util/glob"
- kubeutil "github.com/argoproj/argo-cd/v3/util/kube"
- "github.com/argoproj/argo-cd/v3/util/settings"
- "github.com/argoproj/argo-cd/v3/util/text/label"
+ cmdutil "github.com/argoproj/argo-cd/v2/cmd/util"
+ "github.com/argoproj/argo-cd/v2/common"
+ "github.com/argoproj/argo-cd/v2/controller/sharding"
+ argocdclient "github.com/argoproj/argo-cd/v2/pkg/apiclient"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/pkg/client/clientset/versioned"
+ "github.com/argoproj/argo-cd/v2/util/argo"
+ 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/cli"
+ "github.com/argoproj/argo-cd/v2/util/clusterauth"
+ "github.com/argoproj/argo-cd/v2/util/db"
+ "github.com/argoproj/argo-cd/v2/util/errors"
+ "github.com/argoproj/argo-cd/v2/util/glob"
+ kubeutil "github.com/argoproj/argo-cd/v2/util/kube"
+ "github.com/argoproj/argo-cd/v2/util/settings"
+ "github.com/argoproj/argo-cd/v2/util/text/label"
)
func NewClusterCommand(clientOpts *argocdclient.ClientOptions, pathOpts *clientcmd.PathOptions) *cobra.Command {
@@ -78,7 +78,7 @@ type ClusterWithInfo struct {
Namespaces []string
}
-func loadClusters(ctx context.Context, kubeClient kubernetes.Interface, appClient versioned.Interface, replicas int, shardingAlgorithm string, namespace string, portForwardRedis bool, cacheSrc func() (*appstatecache.Cache, error), shard int, redisName string, redisHaProxyName string, redisCompressionStr string) ([]ClusterWithInfo, error) {
+func loadClusters(ctx context.Context, kubeClient *kubernetes.Clientset, appClient *versioned.Clientset, replicas int, shardingAlgorithm string, namespace string, portForwardRedis bool, cacheSrc func() (*appstatecache.Cache, error), shard int, redisName string, redisHaProxyName string, redisCompressionStr string) ([]ClusterWithInfo, error) {
settingsMgr := settings.NewSettingsManager(ctx, kubeClient, namespace)
argoDB := db.NewDB(namespace, settingsMgr, kubeClient)
@@ -86,7 +86,7 @@ func loadClusters(ctx context.Context, kubeClient kubernetes.Interface, appClien
if err != nil {
return nil, err
}
- appItems, err := appClient.ArgoprojV1alpha1().Applications(namespace).List(ctx, metav1.ListOptions{})
+ appItems, err := appClient.ArgoprojV1alpha1().Applications(namespace).List(ctx, v1.ListOptions{})
if err != nil {
return nil, err
}
@@ -123,6 +123,13 @@ func loadClusters(ctx context.Context, kubeClient kubernetes.Interface, appClien
}
apps := appItems.Items
+ for i, app := range apps {
+ err := argo.ValidateDestination(ctx, &app.Spec.Destination, argoDB)
+ if err != nil {
+ return nil, err
+ }
+ apps[i] = app
+ }
clusters := make([]ClusterWithInfo, len(clustersList.Items))
batchSize := 10
@@ -147,11 +154,7 @@ func loadClusters(ctx context.Context, kubeClient kubernetes.Interface, appClien
}
nsSet := map[string]bool{}
for _, app := range apps {
- destCluster, err := argo.GetDestinationCluster(ctx, app.Spec.Destination, argoDB)
- if err != nil {
- return fmt.Errorf("error validating application destination: %w", err)
- }
- if destCluster.Server == cluster.Server {
+ if app.Spec.Destination.Server == cluster.Server {
nsSet[app.Spec.Destination.Namespace] = true
}
}
@@ -169,7 +172,7 @@ func loadClusters(ctx context.Context, kubeClient kubernetes.Interface, appClien
func getControllerReplicas(ctx context.Context, kubeClient *kubernetes.Clientset, namespace string, appControllerName string) (int, error) {
appControllerPodLabelSelector := common.LabelKeyAppName + "=" + appControllerName
- controllerPods, err := kubeClient.CoreV1().Pods(namespace).List(ctx, metav1.ListOptions{
+ controllerPods, err := kubeClient.CoreV1().Pods(namespace).List(ctx, v1.ListOptions{
LabelSelector: appControllerPodLabelSelector,
})
if err != nil {
@@ -190,7 +193,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, _ []string) {
+ Run: func(cmd *cobra.Command, args []string) {
ctx := cmd.Context()
log.SetLevel(log.WarnLevel)
@@ -228,7 +231,7 @@ func NewClusterShardsCommand(clientOpts *argocdclient.ClientOptions) *cobra.Comm
// parse all added flags so far to get the redis-compression flag that was added by AddCacheFlagsToCmd() above
// we can ignore unchecked error here as the command will be parsed again and checked when command.Execute() is run later
- //nolint:errcheck
+ // nolint:errcheck
command.ParseFlags(os.Args[1:])
return &command
}
@@ -271,21 +274,23 @@ func runClusterNamespacesCommand(ctx context.Context, clientConfig clientcmd.Cli
if err != nil {
return fmt.Errorf("error listing clusters: %w", err)
}
- appItems, err := appClient.ArgoprojV1alpha1().Applications(namespace).List(ctx, metav1.ListOptions{})
+ appItems, err := appClient.ArgoprojV1alpha1().Applications(namespace).List(ctx, v1.ListOptions{})
if err != nil {
return fmt.Errorf("error listing application: %w", err)
}
apps := appItems.Items
+ for i, app := range apps {
+ if err := argo.ValidateDestination(ctx, &app.Spec.Destination, argoDB); err != nil {
+ return fmt.Errorf("error validating application destination: %w", err)
+ }
+ apps[i] = app
+ }
+
clusters := map[string][]string{}
for _, cluster := range clustersList.Items {
nsSet := map[string]bool{}
for _, app := range apps {
- destCluster, err := argo.GetDestinationCluster(ctx, app.Spec.Destination, argoDB)
- if err != nil {
- return fmt.Errorf("error validating application destination: %w", err)
- }
-
- if destCluster.Server != cluster.Server {
+ if app.Spec.Destination.Server != cluster.Server {
continue
}
// Use namespaces of actually deployed resources, since some application use dummy target namespace
@@ -314,12 +319,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, _ []string) {
+ Run: func(cmd *cobra.Command, args []string) {
ctx := cmd.Context()
log.SetLevel(log.WarnLevel)
- err := runClusterNamespacesCommand(ctx, clientConfig, func(_ *versioned.Clientset, _ db.ArgoDB, clusters map[string][]string) error {
+ err := runClusterNamespacesCommand(ctx, clientConfig, func(appClient *versioned.Clientset, _ db.ArgoDB, clusters map[string][]string) error {
w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
_, _ = fmt.Fprintf(w, "CLUSTER\tNAMESPACES\n")
@@ -478,7 +483,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, _ []string) {
+ Run: func(cmd *cobra.Command, args []string) {
ctx := cmd.Context()
log.SetLevel(log.WarnLevel)
@@ -514,7 +519,7 @@ argocd admin cluster stats target-cluster`,
// parse all added flags so far to get the redis-compression flag that was added by AddCacheFlagsToCmd() above
// we can ignore unchecked error here as the command will be parsed again and checked when command.Execute() is run later
- //nolint:errcheck
+ // nolint:errcheck
command.ParseFlags(os.Args[1:])
return &command
}
@@ -545,7 +550,7 @@ argocd admin cluster kubeconfig https://cluster-api-url:6443 /path/to/output/kub
c.HelpFunc()(c, args)
os.Exit(1)
}
- serverURL := args[0]
+ serverUrl := args[0]
output := args[1]
conf, err := clientConfig.ClientConfig()
errors.CheckError(err)
@@ -554,7 +559,7 @@ argocd admin cluster kubeconfig https://cluster-api-url:6443 /path/to/output/kub
kubeclientset, err := kubernetes.NewForConfig(conf)
errors.CheckError(err)
- cluster, err := db.NewDB(namespace, settings.NewSettingsManager(ctx, kubeclientset, namespace), kubeclientset).GetCluster(ctx, serverURL)
+ cluster, err := db.NewDB(namespace, settings.NewSettingsManager(ctx, kubeclientset, namespace), kubeclientset).GetCluster(ctx, serverUrl)
errors.CheckError(err)
rawConfig, err := cluster.RawRestConfig()
errors.CheckError(err)
@@ -612,14 +617,13 @@ func NewGenClusterConfigCommand(pathOpts *clientcmd.PathOptions) *cobra.Command
var awsAuthConf *v1alpha1.AWSAuthConfig
var execProviderConf *v1alpha1.ExecProviderConfig
- switch {
- case clusterOpts.AwsClusterName != "":
+ if clusterOpts.AwsClusterName != "" {
awsAuthConf = &v1alpha1.AWSAuthConfig{
ClusterName: clusterOpts.AwsClusterName,
RoleARN: clusterOpts.AwsRoleArn,
Profile: clusterOpts.AwsProfile,
}
- case clusterOpts.ExecProviderCommand != "":
+ } else if clusterOpts.ExecProviderCommand != "" {
execProviderConf = &v1alpha1.ExecProviderConfig{
Command: clusterOpts.ExecProviderCommand,
Args: clusterOpts.ExecProviderArgs,
@@ -627,10 +631,10 @@ func NewGenClusterConfigCommand(pathOpts *clientcmd.PathOptions) *cobra.Command
APIVersion: clusterOpts.ExecProviderAPIVersion,
InstallHint: clusterOpts.ExecProviderInstallHint,
}
- case generateToken:
+ } else if generateToken {
bearerToken, err = GenerateToken(clusterOpts, conf)
errors.CheckError(err)
- case bearerToken == "":
+ } else if bearerToken == "" {
bearerToken = "bearer-token"
}
if clusterOpts.Name != "" {
@@ -663,7 +667,7 @@ func NewGenClusterConfigCommand(pathOpts *clientcmd.PathOptions) *cobra.Command
secName, err := db.URIToSecretName("cluster", clst.Server)
errors.CheckError(err)
- secret, err := kubeClientset.CoreV1().Secrets(ArgoCDNamespace).Get(ctx, secName, metav1.GetOptions{})
+ secret, err := kubeClientset.CoreV1().Secrets(ArgoCDNamespace).Get(ctx, secName, v1.GetOptions{})
errors.CheckError(err)
errors.CheckError(PrintResources(outputFormat, os.Stdout, secret))
diff --git a/cmd/argocd/commands/admin/cluster_test.go b/cmd/argocd/commands/admin/cluster_test.go
deleted file mode 100644
index 5550dd4331..0000000000
--- a/cmd/argocd/commands/admin/cluster_test.go
+++ /dev/null
@@ -1,81 +0,0 @@
-package admin
-
-import (
- "testing"
- "time"
-
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- fakeapps "github.com/argoproj/argo-cd/v3/pkg/client/clientset/versioned/fake"
- cacheutil "github.com/argoproj/argo-cd/v3/util/cache"
- "github.com/argoproj/argo-cd/v3/util/cache/appstate"
-
- "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/client-go/kubernetes/fake"
- "k8s.io/utils/ptr"
-)
-
-func Test_loadClusters(t *testing.T) {
- argoCDCM := &corev1.ConfigMap{
- ObjectMeta: metav1.ObjectMeta{
- Name: "argocd-cm",
- Namespace: "argocd",
- Labels: map[string]string{
- "app.kubernetes.io/part-of": "argocd",
- },
- },
- Data: map[string]string{},
- }
- argoCDSecret := &corev1.Secret{
- ObjectMeta: metav1.ObjectMeta{
- Name: "argocd-secret",
- Namespace: "argocd",
- },
- Data: map[string][]byte{
- "server.secretkey": []byte("test"),
- },
- }
- app := &v1alpha1.Application{
- ObjectMeta: metav1.ObjectMeta{
- Name: "test",
- Namespace: "argocd",
- },
- Spec: v1alpha1.ApplicationSpec{
- Project: "default",
- Destination: v1alpha1.ApplicationDestination{
- Server: "https://kubernetes.default.svc",
- Namespace: "test",
- },
- },
- }
- ctx := t.Context()
- kubeClient := fake.NewClientset(argoCDCM, argoCDSecret)
- appClient := fakeapps.NewSimpleClientset(app)
- cacheSrc := func() (*appstate.Cache, error) {
- return appstate.NewCache(cacheutil.NewCache(cacheutil.NewInMemoryCache(time.Minute)), time.Minute), nil
- }
- clusters, err := loadClusters(ctx, kubeClient, appClient, 3, "", "argocd", false, cacheSrc, 0, "", "", "")
- require.NoError(t, err)
- for i := range clusters {
- // This changes, nil it to avoid testing it.
- //nolint:staticcheck
- clusters[i].ConnectionState.ModifiedAt = nil
- }
-
- expected := []ClusterWithInfo{{
- Cluster: v1alpha1.Cluster{
- ID: "",
- Server: "https://kubernetes.default.svc",
- Name: "in-cluster",
- ConnectionState: v1alpha1.ConnectionState{
- Status: "Successful",
- },
- ServerVersion: ".",
- Shard: ptr.To(int64(0)),
- },
- Namespaces: []string{"test"},
- }}
- assert.Equal(t, expected, clusters)
-}
diff --git a/cmd/argocd/commands/admin/dashboard.go b/cmd/argocd/commands/admin/dashboard.go
index 02cb4e797f..5ac701beaa 100644
--- a/cmd/argocd/commands/admin/dashboard.go
+++ b/cmd/argocd/commands/admin/dashboard.go
@@ -6,13 +6,13 @@ import (
"github.com/spf13/cobra"
"k8s.io/client-go/tools/clientcmd"
- "github.com/argoproj/argo-cd/v3/util/cli"
+ "github.com/argoproj/argo-cd/v2/util/cli"
- "github.com/argoproj/argo-cd/v3/cmd/argocd/commands/headless"
- "github.com/argoproj/argo-cd/v3/cmd/argocd/commands/initialize"
- "github.com/argoproj/argo-cd/v3/common"
- argocdclient "github.com/argoproj/argo-cd/v3/pkg/apiclient"
- "github.com/argoproj/argo-cd/v3/util/errors"
+ "github.com/argoproj/argo-cd/v2/cmd/argocd/commands/headless"
+ "github.com/argoproj/argo-cd/v2/cmd/argocd/commands/initialize"
+ "github.com/argoproj/argo-cd/v2/common"
+ argocdclient "github.com/argoproj/argo-cd/v2/pkg/apiclient"
+ "github.com/argoproj/argo-cd/v2/util/errors"
)
func NewDashboardCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command {
@@ -24,7 +24,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, _ []string) {
+ Run: func(cmd *cobra.Command, args []string) {
ctx := cmd.Context()
clientOpts.Core = true
diff --git a/cmd/argocd/commands/admin/generatespec_utils.go b/cmd/argocd/commands/admin/generatespec_utils.go
index 71b2883a98..f9d902111a 100644
--- a/cmd/argocd/commands/admin/generatespec_utils.go
+++ b/cmd/argocd/commands/admin/generatespec_utils.go
@@ -8,22 +8,22 @@ import (
"os"
"github.com/argoproj/gitops-engine/pkg/utils/kube"
- corev1 "k8s.io/api/core/v1"
+ v1 "k8s.io/api/core/v1"
"sigs.k8s.io/yaml"
- utilio "github.com/argoproj/argo-cd/v3/util/io"
+ ioutil "github.com/argoproj/argo-cd/v2/util/io"
)
func getOutWriter(inline bool, filePath string) (io.Writer, io.Closer, error) {
if !inline {
- return os.Stdout, utilio.NopCloser, nil
+ return os.Stdout, ioutil.NopCloser, nil
}
if filePath == "" {
- return nil, nil, errors.New("the file path must be specified using flag '--file'")
+ return nil, nil, errors.New("The file path must be specified using flag '--file'")
}
- err := os.Rename(filePath, filePath+".back")
+ err := os.Rename(filePath, fmt.Sprintf("%s.back", filePath))
if err != nil {
return nil, nil, err
}
@@ -36,9 +36,9 @@ 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 {
+func PrintResources(output string, out io.Writer, resources ...interface{}) error {
for i, resource := range resources {
- if secret, ok := resource.(*corev1.Secret); ok {
+ if secret, ok := resource.(*v1.Secret); ok {
convertSecretData(secret)
}
filteredResource, err := omitFields(resource)
@@ -47,7 +47,7 @@ func PrintResources(output string, out io.Writer, resources ...any) error {
}
resources[i] = filteredResource
}
- var obj any = resources
+ var obj interface{} = resources
if len(resources) == 1 {
obj = resources[0]
}
@@ -74,13 +74,13 @@ func PrintResources(output string, out io.Writer, resources ...any) error {
}
// omit fields such as status, creationTimestamp and metadata.namespace in k8s objects
-func omitFields(resource any) (any, error) {
+func omitFields(resource interface{}) (interface{}, error) {
jsonBytes, err := json.Marshal(resource)
if err != nil {
return nil, err
}
- toMap := make(map[string]any)
+ toMap := make(map[string]interface{})
err = json.Unmarshal(jsonBytes, &toMap)
if err != nil {
return nil, err
@@ -88,7 +88,7 @@ func omitFields(resource any) (any, error) {
delete(toMap, "status")
if v, ok := toMap["metadata"]; ok {
- if metadata, ok := v.(map[string]any); ok {
+ if metadata, ok := v.(map[string]interface{}); ok {
delete(metadata, "creationTimestamp")
delete(metadata, "namespace")
}
@@ -97,7 +97,7 @@ func omitFields(resource any) (any, error) {
}
// convertSecretData converts kubernetes secret's data to stringData
-func convertSecretData(secret *corev1.Secret) {
+func convertSecretData(secret *v1.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 5598f89018..9c5735df58 100644
--- a/cmd/argocd/commands/admin/generatespec_utils_test.go
+++ b/cmd/argocd/commands/admin/generatespec_utils_test.go
@@ -2,21 +2,22 @@ package admin
import (
"bytes"
+ "fmt"
"os"
"testing"
- utilio "github.com/argoproj/argo-cd/v3/util/io"
+ "github.com/argoproj/argo-cd/v2/util/io"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
- corev1 "k8s.io/api/core/v1"
+ v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
func TestGetOutWriter_InlineOff(t *testing.T) {
out, closer, err := getOutWriter(false, "")
require.NoError(t, err)
- defer utilio.Close(closer)
+ defer io.Close(closer)
assert.Equal(t, os.Stdout, out)
}
@@ -24,21 +25,21 @@ func TestGetOutWriter_InlineOff(t *testing.T) {
func TestGetOutWriter_InlineOn(t *testing.T) {
tmpFile := t.TempDir()
defer func() {
- _ = os.Remove(tmpFile + ".back")
+ _ = os.Remove(fmt.Sprintf("%s.back", tmpFile))
}()
out, closer, err := getOutWriter(true, tmpFile)
require.NoError(t, err)
- defer utilio.Close(closer)
+ defer io.Close(closer)
assert.Equal(t, tmpFile, out.(*os.File).Name())
- _, err = os.Stat(tmpFile + ".back")
+ _, err = os.Stat(fmt.Sprintf("%s.back", tmpFile))
require.NoError(t, err, "Back file must be created")
}
func TestPrintResources_Secret_YAML(t *testing.T) {
out := bytes.Buffer{}
- err := PrintResources("yaml", &out, &corev1.Secret{
+ err := PrintResources("yaml", &out, &v1.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/initial_password.go b/cmd/argocd/commands/admin/initial_password.go
index 6b019f5f5a..bcd699d3d0 100644
--- a/cmd/argocd/commands/admin/initial_password.go
+++ b/cmd/argocd/commands/admin/initial_password.go
@@ -5,12 +5,12 @@ import (
"fmt"
"github.com/spf13/cobra"
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+ v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
- "github.com/argoproj/argo-cd/v3/util/cli"
- "github.com/argoproj/argo-cd/v3/util/errors"
+ "github.com/argoproj/argo-cd/v2/util/cli"
+ "github.com/argoproj/argo-cd/v2/util/errors"
)
const initialPasswordSecretName = "argocd-initial-admin-secret"
@@ -21,14 +21,14 @@ 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(_ *cobra.Command, _ []string) {
+ Run: func(c *cobra.Command, args []string) {
config, err := clientConfig.ClientConfig()
errors.CheckError(err)
namespace, _, err := clientConfig.Namespace()
errors.CheckError(err)
kubeClientset := kubernetes.NewForConfigOrDie(config)
- secret, err := kubeClientset.CoreV1().Secrets(namespace).Get(context.Background(), initialPasswordSecretName, metav1.GetOptions{})
+ secret, err := kubeClientset.CoreV1().Secrets(namespace).Get(context.Background(), initialPasswordSecretName, v1.GetOptions{})
errors.CheckError(err)
if initialPass, ok := secret.Data["password"]; ok {
diff --git a/cmd/argocd/commands/admin/notifications.go b/cmd/argocd/commands/admin/notifications.go
index 08837db9c5..32ae589270 100644
--- a/cmd/argocd/commands/admin/notifications.go
+++ b/cmd/argocd/commands/admin/notifications.go
@@ -1,23 +1,24 @@
package admin
import (
+ "fmt"
"log"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
- "github.com/argoproj/argo-cd/v3/common"
- "github.com/argoproj/argo-cd/v3/reposerver/apiclient"
- "github.com/argoproj/argo-cd/v3/util/env"
- service "github.com/argoproj/argo-cd/v3/util/notification/argocd"
- "github.com/argoproj/argo-cd/v3/util/notification/settings"
- "github.com/argoproj/argo-cd/v3/util/tls"
+ "github.com/argoproj/argo-cd/v2/common"
+ "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/tls"
"github.com/argoproj/notifications-engine/pkg/cmd"
"github.com/spf13/cobra"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application"
)
var applications = schema.GroupVersionResource{Group: application.Group, Version: "v1alpha1", Resource: application.ApplicationPlural}
@@ -50,8 +51,8 @@ func NewNotificationsCommand() *cobra.Command {
}
if !tlsConfig.DisableTLS && tlsConfig.StrictValidation {
pool, err := tls.LoadX509CertPool(
- env.StringFromEnv(common.EnvAppConfigPath, common.DefaultAppConfigPath)+"/reposerver/tls/tls.crt",
- env.StringFromEnv(common.EnvAppConfigPath, common.DefaultAppConfigPath)+"/reposerver/tls/ca.crt",
+ fmt.Sprintf("%s/reposerver/tls/tls.crt", env.StringFromEnv(common.EnvAppConfigPath, common.DefaultAppConfigPath)),
+ fmt.Sprintf("%s/reposerver/tls/ca.crt", env.StringFromEnv(common.EnvAppConfigPath, common.DefaultAppConfigPath)),
)
if err != nil {
log.Fatalf("Failed to load tls certs: %v", err)
diff --git a/cmd/argocd/commands/admin/project.go b/cmd/argocd/commands/admin/project.go
index 9381ed4ad2..3570afbb1a 100644
--- a/cmd/argocd/commands/admin/project.go
+++ b/cmd/argocd/commands/admin/project.go
@@ -2,24 +2,23 @@ package admin
import (
"context"
- stderrors "errors"
"fmt"
"os"
"path/filepath"
"strings"
- cmdutil "github.com/argoproj/argo-cd/v3/cmd/util"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- appclientset "github.com/argoproj/argo-cd/v3/pkg/client/clientset/versioned"
- appclient "github.com/argoproj/argo-cd/v3/pkg/client/clientset/versioned/typed/application/v1alpha1"
- "github.com/argoproj/argo-cd/v3/util/cli"
- "github.com/argoproj/argo-cd/v3/util/errors"
- utilio "github.com/argoproj/argo-cd/v3/util/io"
- "github.com/argoproj/argo-cd/v3/util/templates"
+ cmdutil "github.com/argoproj/argo-cd/v2/cmd/util"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+ appclientset "github.com/argoproj/argo-cd/v2/pkg/client/clientset/versioned"
+ appclient "github.com/argoproj/argo-cd/v2/pkg/client/clientset/versioned/typed/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/util/cli"
+ "github.com/argoproj/argo-cd/v2/util/errors"
+ "github.com/argoproj/argo-cd/v2/util/io"
+ "github.com/argoproj/argo-cd/v2/util/templates"
"github.com/argoproj/gitops-engine/pkg/utils/kube"
"github.com/spf13/cobra"
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+ v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/tools/clientcmd"
)
@@ -66,7 +65,7 @@ func NewGenProjectSpecCommand() *cobra.Command {
out, closer, err := getOutWriter(inline, fileURL)
errors.CheckError(err)
- defer utilio.Close(closer)
+ defer io.Close(closer)
errors.CheckError(PrintResources(outputFormat, out, proj))
},
@@ -97,16 +96,16 @@ func getModification(modification string, resource string, scope string, permiss
switch modification {
case "set":
if scope == "" {
- return nil, stderrors.New("flag --group cannot be empty if permission should be set in role")
+ return nil, fmt.Errorf("Flag --group cannot be empty if permission should be set in role")
}
if permission == "" {
- return nil, stderrors.New("flag --permission cannot be empty if permission should be set in role")
+ return nil, fmt.Errorf("Flag --permission cannot be empty if permission should be set in role")
}
return func(proj string, action string) string {
return fmt.Sprintf("%s, %s, %s/%s, %s", resource, action, proj, scope, permission)
}, nil
case "remove":
- return func(_ string, _ string) string {
+ return func(proj string, action string) string {
return ""
}, nil
}
@@ -123,7 +122,7 @@ func saveProject(ctx context.Context, updated v1alpha1.AppProject, orig v1alpha1
}
_ = cli.PrintDiff(updated.Name, target, live)
if !dryRun {
- _, err = projectsIf.Update(ctx, &updated, metav1.UpdateOptions{})
+ _, err = projectsIf.Update(ctx, &updated, v1.UpdateOptions{})
if err != nil {
return fmt.Errorf("error while updating project: %w", err)
}
@@ -199,7 +198,7 @@ func NewUpdatePolicyRuleCommand() *cobra.Command {
}
func updateProjects(ctx context.Context, projIf appclient.AppProjectInterface, projectGlob string, rolePattern string, action string, modification func(string, string) string, dryRun bool) error {
- projects, err := projIf.List(ctx, metav1.ListOptions{})
+ projects, err := projIf.List(ctx, v1.ListOptions{})
if err != nil {
return fmt.Errorf("error listing the projects: %w", err)
}
@@ -223,14 +222,13 @@ func updateProjects(ctx context.Context, projIf appclient.AppProjectInterface, p
break
}
policyPermission := modification(proj.Name, action)
- switch {
- case actionPolicyIndex == -1 && policyPermission != "":
+ if actionPolicyIndex == -1 && policyPermission != "" {
updated = true
role.Policies = append(role.Policies, formatPolicy(proj.Name, role.Name, policyPermission))
- case actionPolicyIndex > -1 && policyPermission == "":
+ } else if actionPolicyIndex > -1 && policyPermission == "" {
updated = true
role.Policies = append(role.Policies[:actionPolicyIndex], role.Policies[actionPolicyIndex+1:]...)
- case actionPolicyIndex > -1 && policyPermission != "":
+ } else if actionPolicyIndex > -1 && policyPermission != "" {
updated = true
role.Policies[actionPolicyIndex] = formatPolicy(proj.Name, role.Name, policyPermission)
}
diff --git a/cmd/argocd/commands/admin/project_allowlist.go b/cmd/argocd/commands/admin/project_allowlist.go
index 7caca31d92..9f436f2f3a 100644
--- a/cmd/argocd/commands/admin/project_allowlist.go
+++ b/cmd/argocd/commands/admin/project_allowlist.go
@@ -17,10 +17,10 @@ import (
"k8s.io/client-go/tools/clientcmd"
"sigs.k8s.io/yaml"
- "github.com/argoproj/argo-cd/v3/util/errors"
+ "github.com/argoproj/argo-cd/v2/util/errors"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- "github.com/argoproj/argo-cd/v3/util/cli"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/util/cli"
// load the gcp plugin (required to authenticate against GKE clusters).
_ "k8s.io/client-go/plugin/pkg/client/auth/gcp"
@@ -29,7 +29,7 @@ import (
// load the azure plugin (required to authenticate with AKS clusters).
_ "k8s.io/client-go/plugin/pkg/client/auth/azure"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application"
)
// NewProjectAllowListGenCommand generates a project from clusterRole
@@ -136,17 +136,17 @@ func generateProjectAllowList(serverResources []*metav1.APIResourceList, cluster
continue
}
- ruleAPIGroup := rule.APIGroups[0]
+ ruleApiGroup := rule.APIGroups[0]
for _, ruleResource := range rule.Resources {
for _, apiResourcesList := range serverResources {
gv, err := schema.ParseGroupVersion(apiResourcesList.GroupVersion)
if err != nil {
gv = schema.GroupVersion{}
}
- if ruleAPIGroup == gv.Group {
+ if ruleApiGroup == gv.Group {
for _, apiResource := range apiResourcesList.APIResources {
if apiResource.Name == ruleResource {
- resourceList = append(resourceList, metav1.GroupKind{Group: ruleAPIGroup, Kind: apiResource.Kind})
+ resourceList = append(resourceList, metav1.GroupKind{Group: ruleApiGroup, Kind: apiResource.Kind})
}
}
}
diff --git a/cmd/argocd/commands/admin/project_test.go b/cmd/argocd/commands/admin/project_test.go
index 3e0b7c10e9..341cd48f5c 100644
--- a/cmd/argocd/commands/admin/project_test.go
+++ b/cmd/argocd/commands/admin/project_test.go
@@ -1,14 +1,15 @@
package admin
import (
+ "context"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+ v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- "github.com/argoproj/argo-cd/v3/pkg/client/clientset/versioned/fake"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/pkg/client/clientset/versioned/fake"
)
const (
@@ -20,7 +21,7 @@ func newProj(name string, roleNames ...string) *v1alpha1.AppProject {
for i := range roleNames {
roles = append(roles, v1alpha1.ProjectRole{Name: roleNames[i]})
}
- return &v1alpha1.AppProject{ObjectMeta: metav1.ObjectMeta{
+ return &v1alpha1.AppProject{ObjectMeta: v1.ObjectMeta{
Name: name,
Namespace: namespace,
}, Spec: v1alpha1.AppProjectSpec{
@@ -29,7 +30,7 @@ func newProj(name string, roleNames ...string) *v1alpha1.AppProject {
}
func TestUpdateProjects_FindMatchingProject(t *testing.T) {
- ctx := t.Context()
+ ctx := context.Background()
clientset := fake.NewSimpleClientset(newProj("foo", "test"), newProj("bar", "test"))
@@ -38,17 +39,17 @@ func TestUpdateProjects_FindMatchingProject(t *testing.T) {
err = updateProjects(ctx, clientset.ArgoprojV1alpha1().AppProjects(namespace), "ba*", "*", "set", modification, false)
require.NoError(t, err)
- fooProj, err := clientset.ArgoprojV1alpha1().AppProjects(namespace).Get(ctx, "foo", metav1.GetOptions{})
+ fooProj, err := clientset.ArgoprojV1alpha1().AppProjects(namespace).Get(ctx, "foo", v1.GetOptions{})
require.NoError(t, err)
assert.Empty(t, fooProj.Spec.Roles[0].Policies)
- barProj, err := clientset.ArgoprojV1alpha1().AppProjects(namespace).Get(ctx, "bar", metav1.GetOptions{})
+ barProj, err := clientset.ArgoprojV1alpha1().AppProjects(namespace).Get(ctx, "bar", v1.GetOptions{})
require.NoError(t, err)
- assert.Equal(t, []string{"p, proj:bar:test, *, set, bar/*, allow"}, barProj.Spec.Roles[0].Policies)
+ assert.EqualValues(t, []string{"p, proj:bar:test, *, set, bar/*, allow"}, barProj.Spec.Roles[0].Policies)
}
func TestUpdateProjects_FindMatchingRole(t *testing.T) {
- ctx := t.Context()
+ ctx := context.Background()
clientset := fake.NewSimpleClientset(newProj("proj", "foo", "bar"))
@@ -57,9 +58,9 @@ func TestUpdateProjects_FindMatchingRole(t *testing.T) {
err = updateProjects(ctx, clientset.ArgoprojV1alpha1().AppProjects(namespace), "*", "fo*", "set", modification, false)
require.NoError(t, err)
- proj, err := clientset.ArgoprojV1alpha1().AppProjects(namespace).Get(ctx, "proj", metav1.GetOptions{})
+ proj, err := clientset.ArgoprojV1alpha1().AppProjects(namespace).Get(ctx, "proj", v1.GetOptions{})
require.NoError(t, err)
- assert.Equal(t, []string{"p, proj:proj:foo, *, set, proj/*, allow"}, proj.Spec.Roles[0].Policies)
+ assert.EqualValues(t, []string{"p, proj:proj:foo, *, set, proj/*, allow"}, proj.Spec.Roles[0].Policies)
assert.Empty(t, proj.Spec.Roles[1].Policies)
}
@@ -74,7 +75,7 @@ func TestGetModification_RemovePolicy(t *testing.T) {
modification, err := getModification("remove", "*", "*", "allow")
require.NoError(t, err)
policy := modification("proj", "myaction")
- assert.Empty(t, policy)
+ assert.Equal(t, "", policy)
}
func TestGetModification_NotSupported(t *testing.T) {
diff --git a/cmd/argocd/commands/admin/redis_initial_password.go b/cmd/argocd/commands/admin/redis_initial_password.go
index 96c29017c7..f54741773f 100644
--- a/cmd/argocd/commands/admin/redis_initial_password.go
+++ b/cmd/argocd/commands/admin/redis_initial_password.go
@@ -8,15 +8,16 @@ import (
"github.com/spf13/cobra"
corev1 "k8s.io/api/core/v1"
- apierrors "k8s.io/apimachinery/pkg/api/errors"
+ apierr "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+ v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
- "github.com/argoproj/argo-cd/v3/common"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- "github.com/argoproj/argo-cd/v3/util/cli"
- "github.com/argoproj/argo-cd/v3/util/errors"
+ "github.com/argoproj/argo-cd/v2/common"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/util/cli"
+ "github.com/argoproj/argo-cd/v2/util/errors"
)
func generateRandomPassword() (string, error) {
@@ -40,7 +41,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(_ *cobra.Command, _ []string) {
+ Run: func(c *cobra.Command, args []string) {
namespace, _, err := clientConfig.Namespace()
errors.CheckError(err)
@@ -74,18 +75,19 @@ func NewRedisInitialPasswordCommand() *cobra.Command {
Type: corev1.SecretTypeOpaque,
}
_, err = kubeClientset.CoreV1().Secrets(namespace).Create(context.Background(), secret, metav1.CreateOptions{})
- if err != nil && !apierrors.IsAlreadyExists(err) {
+ if err != nil && !apierr.IsAlreadyExists(err) {
errors.CheckError(err)
}
fmt.Printf("Argo CD Redis secret state confirmed: secret name %s.\n", redisInitialCredentials)
- secret, err = kubeClientset.CoreV1().Secrets(namespace).Get(context.Background(), redisInitialCredentials, metav1.GetOptions{})
+ secret, err = kubeClientset.CoreV1().Secrets(namespace).Get(context.Background(), redisInitialCredentials, v1.GetOptions{})
errors.CheckError(err)
if _, ok := secret.Data[redisInitialCredentialsKey]; ok {
fmt.Println("Password secret is configured properly.")
} else {
- errors.Fatal(errors.ErrorGeneric, fmt.Sprintf("key %s doesn't exist in secret %s. \n", redisInitialCredentialsKey, redisInitialCredentials))
+ err := fmt.Errorf("key %s doesn't exist in secret %s. \n", redisInitialCredentialsKey, redisInitialCredentials)
+ errors.CheckError(err)
}
},
}
diff --git a/cmd/argocd/commands/admin/repo.go b/cmd/argocd/commands/admin/repo.go
index e3e00368a2..84933ab0c0 100644
--- a/cmd/argocd/commands/admin/repo.go
+++ b/cmd/argocd/commands/admin/repo.go
@@ -1,22 +1,22 @@
package admin
import (
- stderrors "errors"
+ "fmt"
"os"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
- corev1 "k8s.io/api/core/v1"
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+ apiv1 "k8s.io/api/core/v1"
+ v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes/fake"
- cmdutil "github.com/argoproj/argo-cd/v3/cmd/util"
- "github.com/argoproj/argo-cd/v3/common"
- "github.com/argoproj/argo-cd/v3/util/cli"
- "github.com/argoproj/argo-cd/v3/util/db"
- "github.com/argoproj/argo-cd/v3/util/errors"
- "github.com/argoproj/argo-cd/v3/util/git"
- "github.com/argoproj/argo-cd/v3/util/settings"
+ cmdutil "github.com/argoproj/argo-cd/v2/cmd/util"
+ "github.com/argoproj/argo-cd/v2/common"
+ "github.com/argoproj/argo-cd/v2/util/cli"
+ "github.com/argoproj/argo-cd/v2/util/db"
+ "github.com/argoproj/argo-cd/v2/util/errors"
+ "github.com/argoproj/argo-cd/v2/util/git"
+ "github.com/argoproj/argo-cd/v2/util/settings"
)
const (
@@ -54,9 +54,6 @@ func NewGenRepoSpecCommand() *cobra.Command {
# Add a private Git repository via HTTPS using username/password and TLS client certificates:
argocd admin repo generate-spec https://git.example.com/repos/repo --username git --password secret --tls-client-cert-path ~/mycert.crt --tls-client-cert-key-path ~/mycert.key
- # Add a private Git BitBucket Data Center repository via HTTPS using bearer token:
- argocd admin repo generate-spec https://bitbucket.example.com/scm/proj/repo --bearer-token secret-token
-
# Add a private Git repository via HTTPS using username/password without verifying the server's TLS certificate
argocd admin repo generate-spec https://git.example.com/repos/repo --username git --password secret --insecure-skip-server-verification
@@ -95,7 +92,7 @@ func NewGenRepoSpecCommand() *cobra.Command {
}
repoOpts.Repo.SSHPrivateKey = string(keyData)
} else {
- err := stderrors.New("--ssh-private-key-path is only supported for SSH repositories")
+ err := fmt.Errorf("--ssh-private-key-path is only supported for SSH repositories")
errors.CheckError(err)
}
}
@@ -103,7 +100,7 @@ func NewGenRepoSpecCommand() *cobra.Command {
// tls-client-cert-path and tls-client-cert-key-key-path must always be
// specified together
if (repoOpts.TlsClientCertPath != "" && repoOpts.TlsClientCertKeyPath == "") || (repoOpts.TlsClientCertPath == "" && repoOpts.TlsClientCertKeyPath != "") {
- err := stderrors.New("--tls-client-cert-path and --tls-client-cert-key-path must be specified together")
+ err := fmt.Errorf("--tls-client-cert-path and --tls-client-cert-key-path must be specified together")
errors.CheckError(err)
}
@@ -117,7 +114,7 @@ func NewGenRepoSpecCommand() *cobra.Command {
repoOpts.Repo.TLSClientCertData = string(tlsCertData)
repoOpts.Repo.TLSClientCertKey = string(tlsCertKey)
} else {
- err := stderrors.New("--tls-client-cert-path is only supported for HTTPS repositories")
+ err := fmt.Errorf("--tls-client-cert-path is only supported for HTTPS repositories")
errors.CheckError(err)
}
}
@@ -129,10 +126,9 @@ func NewGenRepoSpecCommand() *cobra.Command {
repoOpts.Repo.Insecure = repoOpts.InsecureSkipServerVerification
repoOpts.Repo.EnableLFS = repoOpts.EnableLfs
repoOpts.Repo.EnableOCI = repoOpts.EnableOci
- repoOpts.Repo.UseAzureWorkloadIdentity = repoOpts.UseAzureWorkloadIdentity
if repoOpts.Repo.Type == "helm" && repoOpts.Repo.Name == "" {
- errors.CheckError(stderrors.New("must specify --name for repos of type 'helm'"))
+ errors.CheckError(fmt.Errorf("must specify --name for repos of type 'helm'"))
}
// If the user set a username, but didn't supply password via --password,
@@ -141,19 +137,12 @@ func NewGenRepoSpecCommand() *cobra.Command {
repoOpts.Repo.Password = cli.PromptPassword(repoOpts.Repo.Password)
}
- err := cmdutil.ValidateBearerTokenAndPasswordCombo(repoOpts.Repo.BearerToken, repoOpts.Repo.Password)
- errors.CheckError(err)
- err = cmdutil.ValidateBearerTokenForHTTPSRepoOnly(repoOpts.Repo.BearerToken, git.IsHTTPSURL(repoOpts.Repo.Repo))
- errors.CheckError(err)
- err = cmdutil.ValidateBearerTokenForGitOnly(repoOpts.Repo.BearerToken, repoOpts.Repo.Type)
- errors.CheckError(err)
-
- argoCDCM := &corev1.ConfigMap{
- TypeMeta: metav1.TypeMeta{
+ argoCDCM := &apiv1.ConfigMap{
+ TypeMeta: v1.TypeMeta{
Kind: "ConfigMap",
APIVersion: "v1",
},
- ObjectMeta: metav1.ObjectMeta{
+ ObjectMeta: v1.ObjectMeta{
Name: common.ArgoCDConfigMapName,
Namespace: ArgoCDNamespace,
Labels: map[string]string{
@@ -165,10 +154,10 @@ func NewGenRepoSpecCommand() *cobra.Command {
settingsMgr := settings.NewSettingsManager(ctx, kubeClientset, ArgoCDNamespace)
argoDB := db.NewDB(ArgoCDNamespace, settingsMgr, kubeClientset)
- _, err = argoDB.CreateRepository(ctx, &repoOpts.Repo)
+ _, err := argoDB.CreateRepository(ctx, &repoOpts.Repo)
errors.CheckError(err)
- secret, err := kubeClientset.CoreV1().Secrets(ArgoCDNamespace).Get(ctx, db.RepoURLToSecretName(repoSecretPrefix, repoOpts.Repo.Repo, repoOpts.Repo.Project), metav1.GetOptions{})
+ secret, err := kubeClientset.CoreV1().Secrets(ArgoCDNamespace).Get(ctx, db.RepoURLToSecretName(repoSecretPrefix, repoOpts.Repo.Repo, repoOpts.Repo.Project), v1.GetOptions{})
errors.CheckError(err)
errors.CheckError(PrintResources(outputFormat, os.Stdout, secret))
diff --git a/cmd/argocd/commands/admin/settings.go b/cmd/argocd/commands/admin/settings.go
index a239de54b0..85baf9bfd1 100644
--- a/cmd/argocd/commands/admin/settings.go
+++ b/cmd/argocd/commands/admin/settings.go
@@ -3,7 +3,6 @@ package admin
import (
"bytes"
"context"
- stderrors "errors"
"fmt"
"os"
"reflect"
@@ -16,21 +15,20 @@ import (
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
corev1 "k8s.io/api/core/v1"
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+ v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/kubernetes/fake"
"k8s.io/client-go/tools/clientcmd"
"sigs.k8s.io/yaml"
- "github.com/argoproj/argo-cd/v3/common"
- applicationpkg "github.com/argoproj/argo-cd/v3/pkg/apiclient/application"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- "github.com/argoproj/argo-cd/v3/util/argo/normalizers"
- "github.com/argoproj/argo-cd/v3/util/cli"
- "github.com/argoproj/argo-cd/v3/util/errors"
- "github.com/argoproj/argo-cd/v3/util/lua"
- "github.com/argoproj/argo-cd/v3/util/settings"
+ "github.com/argoproj/argo-cd/v2/common"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/util/argo/normalizers"
+ "github.com/argoproj/argo-cd/v2/util/cli"
+ "github.com/argoproj/argo-cd/v2/util/errors"
+ "github.com/argoproj/argo-cd/v2/util/lua"
+ "github.com/argoproj/argo-cd/v2/util/settings"
)
type settingsOpts struct {
@@ -53,7 +51,7 @@ func collectLogs(callback func()) string {
return out.String()
}
-func setSettingsMeta(obj metav1.Object) {
+func setSettingsMeta(obj v1.Object) {
obj.SetNamespace("default")
labels := obj.GetLabels()
if labels == nil {
@@ -65,20 +63,19 @@ func setSettingsMeta(obj metav1.Object) {
func (opts *settingsOpts) createSettingsManager(ctx context.Context) (*settings.SettingsManager, error) {
var argocdCM *corev1.ConfigMap
- switch {
- case opts.argocdCMPath == "" && !opts.loadClusterSettings:
- return nil, stderrors.New("either --argocd-cm-path must be provided or --load-cluster-settings must be set to true")
- case opts.argocdCMPath == "":
+ if opts.argocdCMPath == "" && !opts.loadClusterSettings {
+ return nil, fmt.Errorf("either --argocd-cm-path must be provided or --load-cluster-settings must be set to true")
+ } else if opts.argocdCMPath == "" {
realClientset, ns, err := opts.getK8sClient()
if err != nil {
return nil, err
}
- argocdCM, err = realClientset.CoreV1().ConfigMaps(ns).Get(ctx, common.ArgoCDConfigMapName, metav1.GetOptions{})
+ argocdCM, err = realClientset.CoreV1().ConfigMaps(ns).Get(ctx, common.ArgoCDConfigMapName, v1.GetOptions{})
if err != nil {
return nil, err
}
- default:
+ } else {
data, err := os.ReadFile(opts.argocdCMPath)
if err != nil {
return nil, err
@@ -91,8 +88,7 @@ func (opts *settingsOpts) createSettingsManager(ctx context.Context) (*settings.
setSettingsMeta(argocdCM)
var argocdSecret *corev1.Secret
- switch {
- case opts.argocdSecretPath != "":
+ if opts.argocdSecretPath != "" {
data, err := os.ReadFile(opts.argocdSecretPath)
if err != nil {
return nil, err
@@ -102,18 +98,18 @@ func (opts *settingsOpts) createSettingsManager(ctx context.Context) (*settings.
return nil, err
}
setSettingsMeta(argocdSecret)
- case opts.loadClusterSettings:
+ } else if opts.loadClusterSettings {
realClientset, ns, err := opts.getK8sClient()
if err != nil {
return nil, err
}
- argocdSecret, err = realClientset.CoreV1().Secrets(ns).Get(ctx, common.ArgoCDSecretName, metav1.GetOptions{})
+ argocdSecret, err = realClientset.CoreV1().Secrets(ns).Get(ctx, common.ArgoCDSecretName, v1.GetOptions{})
if err != nil {
return nil, err
}
- default:
+ } else {
argocdSecret = &corev1.Secret{
- ObjectMeta: metav1.ObjectMeta{
+ ObjectMeta: v1.ObjectMeta{
Name: common.ArgoCDSecretName,
},
Data: map[string][]byte{
@@ -163,7 +159,7 @@ func NewSettingsCommand() *cobra.Command {
command.AddCommand(NewValidateSettingsCommand(&opts))
command.AddCommand(NewResourceOverridesCommand(&opts))
- command.AddCommand(NewRBACCommand())
+ command.AddCommand(NewRBACCommand(&opts))
opts.clientConfig = cli.AddKubectlFlagsToCmd(command)
command.PersistentFlags().StringVar(&opts.argocdCMPath, "argocd-cm-path", "", "Path to local argocd-cm.yaml file")
@@ -215,7 +211,7 @@ var validatorsByGroup = map[string]settingValidator{
}
var summary string
if ssoProvider != "" {
- summary = ssoProvider + " is configured"
+ summary = fmt.Sprintf("%s is configured", ssoProvider)
if general.URL == "" {
summary = summary + " ('url' field is missing)"
}
@@ -248,6 +244,19 @@ var validatorsByGroup = map[string]settingValidator{
}
return summary, err
},
+ "repositories": joinValidators(func(manager *settings.SettingsManager) (string, error) {
+ repos, err := manager.GetRepositories()
+ if err != nil {
+ return "", err
+ }
+ return fmt.Sprintf("%d repositories", len(repos)), nil
+ }, func(manager *settings.SettingsManager) (string, error) {
+ creds, err := manager.GetRepositoryCredentials()
+ if err != nil {
+ return "", err
+ }
+ return fmt.Sprintf("%d repository credentials", len(creds)), nil
+ }),
"accounts": func(manager *settings.SettingsManager) (string, error) {
accounts, err := manager.GetAccounts()
if err != nil {
@@ -285,7 +294,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, _ []string) {
+ Run: func(c *cobra.Command, args []string) {
ctx := c.Context()
settingsManager, err := cmdCtx.createSettingsManager(ctx)
@@ -501,15 +510,15 @@ argocd admin settings resource-overrides health ./deploy.yaml --argocd-cm-path .
os.Exit(1)
}
- executeResourceOverrideCommand(ctx, cmdCtx, args, func(res unstructured.Unstructured, _ v1alpha1.ResourceOverride, overrides map[string]v1alpha1.ResourceOverride) {
+ executeResourceOverrideCommand(ctx, cmdCtx, args, func(res unstructured.Unstructured, override v1alpha1.ResourceOverride, overrides map[string]v1alpha1.ResourceOverride) {
gvk := res.GroupVersionKind()
resHealth, err := healthutil.GetResourceHealth(&res, lua.ResourceHealthOverrides(overrides))
- switch {
- case err != nil:
+
+ if err != nil {
errors.CheckError(err)
- case resHealth == nil:
+ } else if resHealth == nil {
fmt.Printf("Health script is not configured for '%s/%s'\n", gvk.Group, gvk.Kind)
- default:
+ } else {
_, _ = fmt.Printf("STATUS: %s\n", resHealth.Status)
_, _ = fmt.Printf("MESSAGE: %s\n", resHealth.Message)
}
@@ -564,8 +573,6 @@ argocd admin settings resource-overrides action list /tmp/deploy.yaml --argocd-c
}
func NewResourceActionRunCommand(cmdCtx commandContext) *cobra.Command {
- var resourceActionParameters []string
-
command := &cobra.Command{
Use: "run-action RESOURCE_YAML_PATH ACTION",
Aliases: []string{"action"},
@@ -582,23 +589,6 @@ argocd admin settings resource-overrides action /tmp/deploy.yaml restart --argoc
}
action := args[1]
- // Parse resource action parameters
- parsedParams := make([]*applicationpkg.ResourceActionParameters, 0)
- if len(resourceActionParameters) > 0 {
- for _, param := range resourceActionParameters {
- parts := strings.SplitN(param, "=", 2)
- if len(parts) != 2 {
- log.Fatalf("Invalid parameter format: %s", param)
- }
- name := parts[0]
- value := parts[1]
- parsedParams = append(parsedParams, &applicationpkg.ResourceActionParameters{
- Name: &name,
- Value: &value,
- })
- }
- }
-
executeResourceOverrideCommand(ctx, cmdCtx, args, func(res unstructured.Unstructured, override v1alpha1.ResourceOverride, overrides map[string]v1alpha1.ResourceOverride) {
gvk := res.GroupVersionKind()
if override.Actions == "" {
@@ -610,7 +600,7 @@ argocd admin settings resource-overrides action /tmp/deploy.yaml restart --argoc
action, err := luaVM.GetResourceAction(&res, action)
errors.CheckError(err)
- modifiedRes, err := luaVM.ExecuteResourceAction(&res, action.ActionLua, parsedParams)
+ modifiedRes, err := luaVM.ExecuteResourceAction(&res, action.ActionLua)
errors.CheckError(err)
for _, impactedResource := range modifiedRes {
@@ -635,7 +625,5 @@ argocd admin settings resource-overrides action /tmp/deploy.yaml restart --argoc
})
},
}
-
- command.Flags().StringArrayVar(&resourceActionParameters, "param", []string{}, "Action parameters (e.g. --param key1=value1)")
return command
}
diff --git a/cmd/argocd/commands/admin/settings_rbac.go b/cmd/argocd/commands/admin/settings_rbac.go
index e9469a61e6..66fad77b23 100644
--- a/cmd/argocd/commands/admin/settings_rbac.go
+++ b/cmd/argocd/commands/admin/settings_rbac.go
@@ -14,10 +14,11 @@ import (
"k8s.io/client-go/tools/clientcmd"
"sigs.k8s.io/yaml"
- "github.com/argoproj/argo-cd/v3/common"
- "github.com/argoproj/argo-cd/v3/util/assets"
- "github.com/argoproj/argo-cd/v3/util/cli"
- "github.com/argoproj/argo-cd/v3/util/rbac"
+ "github.com/argoproj/argo-cd/v2/common"
+ "github.com/argoproj/argo-cd/v2/util/assets"
+ "github.com/argoproj/argo-cd/v2/util/cli"
+ "github.com/argoproj/argo-cd/v2/util/errors"
+ "github.com/argoproj/argo-cd/v2/util/rbac"
)
type actionTraitMap map[string]rbacTrait
@@ -108,7 +109,7 @@ var extensionActions = actionTraitMap{
}
// NewRBACCommand is the command for 'rbac'
-func NewRBACCommand() *cobra.Command {
+func NewRBACCommand(cmdCtx commandContext) *cobra.Command {
command := &cobra.Command{
Use: "rbac",
Short: "Validate and test RBAC configuration",
@@ -116,13 +117,13 @@ func NewRBACCommand() *cobra.Command {
c.HelpFunc()(c, args)
},
}
- command.AddCommand(NewRBACCanCommand())
+ command.AddCommand(NewRBACCanCommand(cmdCtx))
command.AddCommand(NewRBACValidateCommand())
return command
}
// NewRBACCanCommand is the command for 'rbac can'
-func NewRBACCanCommand() *cobra.Command {
+func NewRBACCanCommand(cmdCtx commandContext) *cobra.Command {
var (
policyFile string
defaultRole string
@@ -208,7 +209,30 @@ argocd admin settings rbac can someuser create application 'default/app' --defau
defaultRole = newDefaultRole
}
- res := checkPolicy(subject, action, resource, subResource, builtinPolicy, userPolicy, defaultRole, matchMode, strict)
+ // Logs RBAC will be enforced only if an internal var serverRBACLogEnforceEnable
+ // (representing server.rbac.log.enforce.enable env var in argocd-cm)
+ // is defined and has a "true" value
+ // Otherwise, no RBAC enforcement for logs will take place (meaning, 'can' request on a logs resource will result in "yes",
+ // even if there is no explicit RBAC allow, or if there is an explicit RBAC deny)
+ var isLogRbacEnforced func() bool
+ if nsOverride && policyFile == "" {
+ if resolveRBACResourceName(resource) == rbac.ResourceLogs {
+ isLogRbacEnforced = func() bool {
+ if opts, ok := cmdCtx.(*settingsOpts); ok {
+ opts.loadClusterSettings = true
+ opts.clientConfig = clientConfig
+ settingsMgr, err := opts.createSettingsManager(ctx)
+ errors.CheckError(err)
+ logEnforceEnable, err := settingsMgr.GetServerRBACLogEnforceEnable()
+ errors.CheckError(err)
+ return logEnforceEnable
+ }
+ return false
+ }
+ }
+ }
+ res := checkPolicy(subject, action, resource, subResource, builtinPolicy, userPolicy, defaultRole, matchMode, strict, isLogRbacEnforced)
+
if res {
if !quiet {
fmt.Println("Yes")
@@ -374,7 +398,7 @@ func getPolicyConfigMap(ctx context.Context, client kubernetes.Interface, namesp
// checkPolicy checks whether given subject is allowed to execute specified
// action against specified resource
-func checkPolicy(subject, action, resource, subResource, builtinPolicy, userPolicy, defaultRole, matchMode string, strict bool) bool {
+func checkPolicy(subject, action, resource, subResource, builtinPolicy, userPolicy, defaultRole, matchMode string, strict bool, isLogRbacEnforced func() bool) bool {
enf := rbac.NewEnforcer(nil, "argocd", "argocd-rbac-cm", nil)
enf.SetDefaultRole(defaultRole)
enf.SetMatchMode(matchMode)
@@ -416,6 +440,11 @@ func checkPolicy(subject, action, resource, subResource, builtinPolicy, userPoli
subResource = "*/*"
}
}
+ if realResource == rbac.ResourceLogs {
+ if isLogRbacEnforced != nil && !isLogRbacEnforced() {
+ return true
+ }
+ }
return enf.Enforce(subject, realResource, action, subResource)
}
diff --git a/cmd/argocd/commands/admin/settings_rbac_test.go b/cmd/argocd/commands/admin/settings_rbac_test.go
index 8b905a11ff..52a6deb2bf 100644
--- a/cmd/argocd/commands/admin/settings_rbac_test.go
+++ b/cmd/argocd/commands/admin/settings_rbac_test.go
@@ -1,6 +1,7 @@
package admin
import (
+ "context"
"os"
"testing"
@@ -13,9 +14,9 @@ import (
"k8s.io/client-go/tools/clientcmd"
clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
- "github.com/argoproj/argo-cd/v3/util/rbac"
+ "github.com/argoproj/argo-cd/v2/util/rbac"
- "github.com/argoproj/argo-cd/v3/util/assets"
+ "github.com/argoproj/argo-cd/v2/util/assets"
)
type FakeClientConfig struct {
@@ -115,7 +116,7 @@ func Test_validateRBACResourceAction(t *testing.T) {
}
func Test_PolicyFromCSV(t *testing.T) {
- ctx := t.Context()
+ ctx := context.Background()
uPol, dRole, matchMode := getPolicy(ctx, "testdata/rbac/policy.csv", nil, "")
require.NotEmpty(t, uPol)
@@ -124,19 +125,27 @@ func Test_PolicyFromCSV(t *testing.T) {
}
func Test_PolicyFromYAML(t *testing.T) {
- ctx := t.Context()
+ ctx := context.Background()
uPol, dRole, matchMode := getPolicy(ctx, "testdata/rbac/argocd-rbac-cm.yaml", nil, "")
require.NotEmpty(t, uPol)
require.Equal(t, "role:unknown", dRole)
require.Empty(t, matchMode)
require.True(t, checkPolicy("my-org:team-qa", "update", "project", "foo",
- "", uPol, dRole, matchMode, true))
+ "", uPol, dRole, matchMode, true, nil))
+}
+
+func trueLogRbacEnforce() bool {
+ return true
+}
+
+func falseLogRbacEnforce() bool {
+ return false
}
func Test_PolicyFromK8s(t *testing.T) {
data, err := os.ReadFile("testdata/rbac/policy.csv")
- ctx := t.Context()
+ ctx := context.Background()
require.NoError(t, err)
kubeclientset := fake.NewClientset(&corev1.ConfigMap{
@@ -152,72 +161,114 @@ func Test_PolicyFromK8s(t *testing.T) {
uPol, dRole, matchMode := getPolicy(ctx, "", kubeclientset, "argocd")
require.NotEmpty(t, uPol)
require.Equal(t, "role:unknown", dRole)
- require.Empty(t, matchMode)
+ require.Equal(t, "", matchMode)
t.Run("get applications", func(t *testing.T) {
- ok := checkPolicy("role:user", "get", "applications", "*/*", assets.BuiltinPolicyCSV, uPol, dRole, "", true)
+ ok := checkPolicy("role:user", "get", "applications", "*/*", assets.BuiltinPolicyCSV, uPol, dRole, "", true, nil)
require.True(t, ok)
})
t.Run("get clusters", func(t *testing.T) {
- ok := checkPolicy("role:user", "get", "clusters", "*", assets.BuiltinPolicyCSV, uPol, dRole, "", true)
+ ok := checkPolicy("role:user", "get", "clusters", "*", assets.BuiltinPolicyCSV, uPol, dRole, "", true, nil)
require.True(t, ok)
})
t.Run("get certificates", func(t *testing.T) {
- ok := checkPolicy("role:user", "get", "certificates", "*", assets.BuiltinPolicyCSV, uPol, dRole, "", true)
+ ok := checkPolicy("role:user", "get", "certificates", "*", assets.BuiltinPolicyCSV, uPol, dRole, "", true, nil)
require.False(t, ok)
})
t.Run("get certificates by default role", func(t *testing.T) {
- ok := checkPolicy("role:user", "get", "certificates", "*", assets.BuiltinPolicyCSV, uPol, "role:readonly", "glob", true)
+ ok := checkPolicy("role:user", "get", "certificates", "*", assets.BuiltinPolicyCSV, uPol, "role:readonly", "glob", true, nil)
require.True(t, ok)
})
t.Run("get certificates by default role without builtin policy", func(t *testing.T) {
- ok := checkPolicy("role:user", "get", "certificates", "*", "", uPol, "role:readonly", "glob", true)
+ ok := checkPolicy("role:user", "get", "certificates", "*", "", uPol, "role:readonly", "glob", true, nil)
require.False(t, ok)
})
t.Run("use regex match mode instead of glob", func(t *testing.T) {
- ok := checkPolicy("role:user", "get", "certificates", ".*", assets.BuiltinPolicyCSV, uPol, "role:readonly", "regex", true)
+ ok := checkPolicy("role:user", "get", "certificates", ".*", assets.BuiltinPolicyCSV, uPol, "role:readonly", "regex", true, nil)
require.False(t, ok)
})
t.Run("get logs", func(t *testing.T) {
- ok := checkPolicy("role:test", "get", "logs", "*/*", assets.BuiltinPolicyCSV, uPol, dRole, "", true)
+ ok := checkPolicy("role:test", "get", "logs", "*/*", assets.BuiltinPolicyCSV, uPol, dRole, "", true, nil)
require.True(t, ok)
})
+ // no function is provided to check if logs rbac is enforced or not, so the policy permissions are queried to determine if no-such-user can get logs
t.Run("no-such-user get logs", func(t *testing.T) {
- ok := checkPolicy("no-such-user", "get", "logs", "*/*", assets.BuiltinPolicyCSV, uPol, dRole, "", true)
+ ok := checkPolicy("no-such-user", "get", "logs", "*/*", assets.BuiltinPolicyCSV, uPol, dRole, "", true, nil)
require.False(t, ok)
})
+ // logs rbac policy is enforced, and no-such-user is not granted logs permission in user policy, so the result should be false (cannot get logs)
+ t.Run("no-such-user get logs rbac enforced", func(t *testing.T) {
+ ok := checkPolicy("no-such-user", "get", "logs", "*/*", assets.BuiltinPolicyCSV, uPol, dRole, "", true, trueLogRbacEnforce)
+ require.False(t, ok)
+ })
+ // no-such-user is not granted logs permission in user policy, but logs rbac policy is not enforced, so logs permission is open to all
+ t.Run("no-such-user get logs rbac not enforced", func(t *testing.T) {
+ ok := checkPolicy("no-such-user", "get", "logs", "*/*", assets.BuiltinPolicyCSV, uPol, dRole, "", true, falseLogRbacEnforce)
+ require.True(t, ok)
+ })
+ // no function is provided to check if logs rbac is enforced or not, so the policy permissions are queried to determine if log-deny-user can get logs
t.Run("log-deny-user get logs", func(t *testing.T) {
- ok := checkPolicy("log-deny-user", "get", "logs", "*/*", assets.BuiltinPolicyCSV, uPol, dRole, "", true)
+ ok := checkPolicy("log-deny-user", "get", "logs", "*/*", assets.BuiltinPolicyCSV, uPol, dRole, "", true, nil)
require.False(t, ok)
})
+ // logs rbac policy is enforced, and log-deny-user is denied logs permission in user policy, so the result should be false (cannot get logs)
+ t.Run("log-deny-user get logs rbac enforced", func(t *testing.T) {
+ ok := checkPolicy("log-deny-user", "get", "logs", "*/*", assets.BuiltinPolicyCSV, uPol, dRole, "", true, trueLogRbacEnforce)
+ require.False(t, ok)
+ })
+ // log-deny-user is denied logs permission in user policy, but logs rbac policy is not enforced, so logs permission is open to all
+ t.Run("log-deny-user get logs rbac not enforced", func(t *testing.T) {
+ ok := checkPolicy("log-deny-user", "get", "logs", "*/*", assets.BuiltinPolicyCSV, uPol, dRole, "", true, falseLogRbacEnforce)
+ require.True(t, ok)
+ })
+ // no function is provided to check if logs rbac is enforced or not, so the policy permissions are queried to determine if log-allow-user can get logs
t.Run("log-allow-user get logs", func(t *testing.T) {
- ok := checkPolicy("log-allow-user", "get", "logs", "*/*", assets.BuiltinPolicyCSV, uPol, dRole, "", true)
+ ok := checkPolicy("log-allow-user", "get", "logs", "*/*", assets.BuiltinPolicyCSV, uPol, dRole, "", true, nil)
+ require.True(t, ok)
+ })
+ // logs rbac policy is enforced, and log-allow-user is granted logs permission in user policy, so the result should be true (can get logs)
+ t.Run("log-allow-user get logs rbac enforced", func(t *testing.T) {
+ ok := checkPolicy("log-allow-user", "get", "logs", "*/*", assets.BuiltinPolicyCSV, uPol, dRole, "", true, trueLogRbacEnforce)
+ require.True(t, ok)
+ })
+ // log-allow-user is granted logs permission in user policy, and logs rbac policy is not enforced, so logs permission is open to all
+ t.Run("log-allow-user get logs rbac not enforced", func(t *testing.T) {
+ ok := checkPolicy("log-allow-user", "get", "logs", "*/*", assets.BuiltinPolicyCSV, uPol, dRole, "", true, falseLogRbacEnforce)
require.True(t, ok)
})
t.Run("get logs", func(t *testing.T) {
- ok := checkPolicy("role:test", "get", "logs", "*", assets.BuiltinPolicyCSV, uPol, dRole, "", true)
+ ok := checkPolicy("role:test", "get", "logs", "*", assets.BuiltinPolicyCSV, uPol, dRole, "", true, nil)
require.True(t, ok)
})
t.Run("get logs", func(t *testing.T) {
- ok := checkPolicy("role:test", "get", "logs", "", assets.BuiltinPolicyCSV, uPol, dRole, "", true)
+ ok := checkPolicy("role:test", "get", "logs", "", assets.BuiltinPolicyCSV, uPol, dRole, "", true, nil)
require.True(t, ok)
})
t.Run("create exec", func(t *testing.T) {
- ok := checkPolicy("role:test", "create", "exec", "*/*", assets.BuiltinPolicyCSV, uPol, dRole, "", true)
+ ok := checkPolicy("role:test", "create", "exec", "*/*", assets.BuiltinPolicyCSV, uPol, dRole, "", true, nil)
require.True(t, ok)
})
t.Run("create applicationsets", func(t *testing.T) {
- ok := checkPolicy("role:user", "create", "applicationsets", "*/*", assets.BuiltinPolicyCSV, uPol, dRole, "", true)
+ ok := checkPolicy("role:user", "create", "applicationsets", "*/*", assets.BuiltinPolicyCSV, uPol, dRole, "", true, nil)
+ require.True(t, ok)
+ })
+ // trueLogRbacEnforce or falseLogRbacEnforce should not affect non-logs resources
+ t.Run("create applicationsets with trueLogRbacEnforce", func(t *testing.T) {
+ ok := checkPolicy("role:user", "create", "applicationsets", "*/*", assets.BuiltinPolicyCSV, uPol, dRole, "", true, trueLogRbacEnforce)
+ require.True(t, ok)
+ })
+ t.Run("create applicationsets with falseLogRbacEnforce", func(t *testing.T) {
+ ok := checkPolicy("role:user", "create", "applicationsets", "*/*", assets.BuiltinPolicyCSV, uPol, dRole, "", true, trueLogRbacEnforce)
require.True(t, ok)
})
t.Run("delete applicationsets", func(t *testing.T) {
- ok := checkPolicy("role:user", "delete", "applicationsets", "*/*", assets.BuiltinPolicyCSV, uPol, dRole, "", true)
+ ok := checkPolicy("role:user", "delete", "applicationsets", "*/*", assets.BuiltinPolicyCSV, uPol, dRole, "", true, nil)
require.True(t, ok)
})
}
func Test_PolicyFromK8sUsingRegex(t *testing.T) {
- ctx := t.Context()
+ ctx := context.Background()
policy := `
p, role:user, clusters, get, .+, allow
@@ -251,49 +302,49 @@ p, role:readonly, certificates, get, .*, allow
p, role:, certificates, get, .*, allow`
t.Run("get applications", func(t *testing.T) {
- ok := checkPolicy("role:user", "get", "applications", ".*/.*", builtInPolicy, uPol, dRole, "regex", true)
+ ok := checkPolicy("role:user", "get", "applications", ".*/.*", builtInPolicy, uPol, dRole, "regex", true, nil)
require.True(t, ok)
})
t.Run("get clusters", func(t *testing.T) {
- ok := checkPolicy("role:user", "get", "clusters", ".*", builtInPolicy, uPol, dRole, "regex", true)
+ ok := checkPolicy("role:user", "get", "clusters", ".*", builtInPolicy, uPol, dRole, "regex", true, nil)
require.True(t, ok)
})
t.Run("get certificates", func(t *testing.T) {
- ok := checkPolicy("role:user", "get", "certificates", ".*", builtInPolicy, uPol, dRole, "regex", true)
+ ok := checkPolicy("role:user", "get", "certificates", ".*", builtInPolicy, uPol, dRole, "regex", true, nil)
require.False(t, ok)
})
t.Run("get certificates by default role", func(t *testing.T) {
- ok := checkPolicy("role:user", "get", "certificates", ".*", builtInPolicy, uPol, "role:readonly", "regex", true)
+ ok := checkPolicy("role:user", "get", "certificates", ".*", builtInPolicy, uPol, "role:readonly", "regex", true, nil)
require.True(t, ok)
})
t.Run("get certificates by default role without builtin policy", func(t *testing.T) {
- ok := checkPolicy("role:user", "get", "certificates", ".*", "", uPol, "role:readonly", "regex", true)
+ ok := checkPolicy("role:user", "get", "certificates", ".*", "", uPol, "role:readonly", "regex", true, nil)
require.False(t, ok)
})
t.Run("use glob match mode instead of regex", func(t *testing.T) {
- ok := checkPolicy("role:user", "get", "certificates", ".+", builtInPolicy, uPol, dRole, "glob", true)
+ ok := checkPolicy("role:user", "get", "certificates", ".+", builtInPolicy, uPol, dRole, "glob", true, nil)
require.False(t, ok)
})
t.Run("get logs via glob match mode", func(t *testing.T) {
- ok := checkPolicy("role:user", "get", "logs", ".*/.*", builtInPolicy, uPol, dRole, "glob", true)
+ ok := checkPolicy("role:user", "get", "logs", ".*/.*", builtInPolicy, uPol, dRole, "glob", true, nil)
require.True(t, ok)
})
t.Run("create exec", func(t *testing.T) {
- ok := checkPolicy("role:user", "create", "exec", ".*/.*", builtInPolicy, uPol, dRole, "regex", true)
+ ok := checkPolicy("role:user", "create", "exec", ".*/.*", builtInPolicy, uPol, dRole, "regex", true, nil)
require.True(t, ok)
})
t.Run("create applicationsets", func(t *testing.T) {
- ok := checkPolicy("role:user", "create", "applicationsets", ".*/.*", builtInPolicy, uPol, dRole, "regex", true)
+ ok := checkPolicy("role:user", "create", "applicationsets", ".*/.*", builtInPolicy, uPol, dRole, "regex", true, nil)
require.True(t, ok)
})
t.Run("delete applicationsets", func(t *testing.T) {
- ok := checkPolicy("role:user", "delete", "applicationsets", ".*/.*", builtInPolicy, uPol, dRole, "regex", true)
+ ok := checkPolicy("role:user", "delete", "applicationsets", ".*/.*", builtInPolicy, uPol, dRole, "regex", true, nil)
require.True(t, ok)
})
}
func TestNewRBACCanCommand(t *testing.T) {
- command := NewRBACCanCommand()
+ command := NewRBACCanCommand(&settingsOpts{})
require.NotNil(t, command)
assert.Equal(t, "can", command.Name())
diff --git a/cmd/argocd/commands/admin/settings_test.go b/cmd/argocd/commands/admin/settings_test.go
index 7418d61cb6..0b37b0bd32 100644
--- a/cmd/argocd/commands/admin/settings_test.go
+++ b/cmd/argocd/commands/admin/settings_test.go
@@ -1,18 +1,20 @@
package admin
import (
+ "bytes"
"context"
+ "fmt"
"io"
"os"
"testing"
- "github.com/argoproj/argo-cd/v3/common"
- utilio "github.com/argoproj/argo-cd/v3/util/io"
- "github.com/argoproj/argo-cd/v3/util/settings"
+ "github.com/argoproj/argo-cd/v2/common"
+ utils "github.com/argoproj/argo-cd/v2/util/io"
+ "github.com/argoproj/argo-cd/v2/util/settings"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
- corev1 "k8s.io/api/core/v1"
+ v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes/fake"
)
@@ -31,7 +33,7 @@ func captureStdout(callback func()) (string, error) {
}()
callback()
- utilio.Close(w)
+ utils.Close(w)
data, err := io.ReadAll(r)
if err != nil {
@@ -43,7 +45,7 @@ func captureStdout(callback func()) (string, error) {
func newSettingsManager(data map[string]string) *settings.SettingsManager {
ctx := context.Background()
- clientset := fake.NewClientset(&corev1.ConfigMap{
+ clientset := fake.NewClientset(&v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Namespace: "default",
Name: common.ArgoCDConfigMapName,
@@ -52,7 +54,7 @@ func newSettingsManager(data map[string]string) *settings.SettingsManager {
},
},
Data: data,
- }, &corev1.Secret{
+ }, &v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Namespace: "default",
Name: common.ArgoCDSecretName,
@@ -67,6 +69,8 @@ func newSettingsManager(data map[string]string) *settings.SettingsManager {
type fakeCmdContext struct {
mgr *settings.SettingsManager
+ // nolint:unused
+ out bytes.Buffer
}
func newCmdContext(data map[string]string) *fakeCmdContext {
@@ -85,7 +89,7 @@ type validatorTestCase struct {
}
func TestCreateSettingsManager(t *testing.T) {
- ctx := t.Context()
+ ctx := context.Background()
f, closer, err := tempFile(`apiVersion: v1
kind: ConfigMap
@@ -94,7 +98,7 @@ metadata:
data:
url: https://myargocd.com`)
require.NoError(t, err)
- defer utilio.Close(closer)
+ defer utils.Close(closer)
opts := settingsOpts{argocdCMPath: f}
settingsManager, err := opts.createSettingsManager(ctx)
@@ -154,6 +158,15 @@ clientSecret: aaaabbbbccccddddeee`,
},
containsSummary: "updated-options",
},
+ "Repositories": {
+ validator: "repositories",
+ data: map[string]string{
+ "repositories": `
+- url: https://github.com/argoproj/my-private-repository1
+- url: https://github.com/argoproj/my-private-repository2`,
+ },
+ containsSummary: "2 repositories",
+ },
"Accounts": {
validator: "accounts",
data: map[string]string{
@@ -243,7 +256,7 @@ func tempFile(content string) (string, io.Closer, error) {
panic(err)
}
}()
- return f.Name(), utilio.NewCloser(func() error {
+ return f.Name(), utils.NewCloser(func() error {
return os.Remove(f.Name())
}), nil
}
@@ -257,14 +270,14 @@ func TestValidateSettingsCommand_NoErrors(t *testing.T) {
require.NoError(t, err)
for k := range validatorsByGroup {
- assert.Contains(t, out, "âś… "+k)
+ assert.Contains(t, out, fmt.Sprintf("âś… %s", k))
}
}
func TestResourceOverrideIgnoreDifferences(t *testing.T) {
f, closer, err := tempFile(testDeploymentYAML)
require.NoError(t, err)
- defer utilio.Close(closer)
+ defer utils.Close(closer)
t.Run("NoOverridesConfigured", func(t *testing.T) {
cmd := NewResourceOverridesCommand(newCmdContext(map[string]string{}))
@@ -297,7 +310,7 @@ func TestResourceOverrideIgnoreDifferences(t *testing.T) {
func TestResourceOverrideHealth(t *testing.T) {
f, closer, err := tempFile(testCustomResourceYAML)
require.NoError(t, err)
- defer utilio.Close(closer)
+ defer utils.Close(closer)
t.Run("NoHealthAssessment", func(t *testing.T) {
cmd := NewResourceOverridesCommand(newCmdContext(map[string]string{
@@ -348,11 +361,11 @@ func TestResourceOverrideHealth(t *testing.T) {
func TestResourceOverrideAction(t *testing.T) {
f, closer, err := tempFile(testDeploymentYAML)
require.NoError(t, err)
- defer utilio.Close(closer)
+ defer utils.Close(closer)
cronJobFile, closer, err := tempFile(testCronJobYAML)
require.NoError(t, err)
- defer utilio.Close(closer)
+ defer utils.Close(closer)
t.Run("NoActions", func(t *testing.T) {
cmd := NewResourceOverridesCommand(newCmdContext(map[string]string{
diff --git a/cmd/argocd/commands/app.go b/cmd/argocd/commands/app.go
index ed24152a62..3cfc5f13f1 100644
--- a/cmd/argocd/commands/app.go
+++ b/cmd/argocd/commands/app.go
@@ -3,7 +3,7 @@ package commands
import (
"context"
"encoding/json"
- stderrors "errors"
+ std_errors "errors"
"fmt"
"io"
"os"
@@ -12,7 +12,6 @@ import (
"sort"
"strconv"
"strings"
- "sync"
"text/tabwriter"
"time"
"unicode/utf8"
@@ -22,7 +21,7 @@ import (
"github.com/argoproj/gitops-engine/pkg/sync/hook"
"github.com/argoproj/gitops-engine/pkg/sync/ignore"
"github.com/argoproj/gitops-engine/pkg/utils/kube"
- grpc_retry "github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/retry"
+ grpc_retry "github.com/grpc-ecosystem/go-grpc-middleware/retry"
"github.com/mattn/go-isatty"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
@@ -36,30 +35,30 @@ import (
"k8s.io/utils/ptr"
"sigs.k8s.io/yaml"
- "github.com/argoproj/argo-cd/v3/cmd/argocd/commands/headless"
- "github.com/argoproj/argo-cd/v3/cmd/argocd/commands/utils"
- cmdutil "github.com/argoproj/argo-cd/v3/cmd/util"
- "github.com/argoproj/argo-cd/v3/controller"
- argocdclient "github.com/argoproj/argo-cd/v3/pkg/apiclient"
- "github.com/argoproj/argo-cd/v3/pkg/apiclient/application"
- clusterpkg "github.com/argoproj/argo-cd/v3/pkg/apiclient/cluster"
- projectpkg "github.com/argoproj/argo-cd/v3/pkg/apiclient/project"
- "github.com/argoproj/argo-cd/v3/pkg/apiclient/settings"
- argoappv1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- repoapiclient "github.com/argoproj/argo-cd/v3/reposerver/apiclient"
- "github.com/argoproj/argo-cd/v3/reposerver/repository"
- "github.com/argoproj/argo-cd/v3/util/argo"
- argodiff "github.com/argoproj/argo-cd/v3/util/argo/diff"
- "github.com/argoproj/argo-cd/v3/util/argo/normalizers"
- "github.com/argoproj/argo-cd/v3/util/cli"
- "github.com/argoproj/argo-cd/v3/util/errors"
- "github.com/argoproj/argo-cd/v3/util/git"
- "github.com/argoproj/argo-cd/v3/util/grpc"
- utilio "github.com/argoproj/argo-cd/v3/util/io"
- logutils "github.com/argoproj/argo-cd/v3/util/log"
- "github.com/argoproj/argo-cd/v3/util/manifeststream"
- "github.com/argoproj/argo-cd/v3/util/templates"
- "github.com/argoproj/argo-cd/v3/util/text/label"
+ "github.com/argoproj/argo-cd/v2/cmd/argocd/commands/headless"
+ "github.com/argoproj/argo-cd/v2/cmd/argocd/commands/utils"
+ cmdutil "github.com/argoproj/argo-cd/v2/cmd/util"
+ "github.com/argoproj/argo-cd/v2/controller"
+ argocdclient "github.com/argoproj/argo-cd/v2/pkg/apiclient"
+ "github.com/argoproj/argo-cd/v2/pkg/apiclient/application"
+ clusterpkg "github.com/argoproj/argo-cd/v2/pkg/apiclient/cluster"
+ projectpkg "github.com/argoproj/argo-cd/v2/pkg/apiclient/project"
+ "github.com/argoproj/argo-cd/v2/pkg/apiclient/settings"
+ argoappv1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+ repoapiclient "github.com/argoproj/argo-cd/v2/reposerver/apiclient"
+ "github.com/argoproj/argo-cd/v2/reposerver/repository"
+ "github.com/argoproj/argo-cd/v2/util/argo"
+ argodiff "github.com/argoproj/argo-cd/v2/util/argo/diff"
+ "github.com/argoproj/argo-cd/v2/util/argo/normalizers"
+ "github.com/argoproj/argo-cd/v2/util/cli"
+ "github.com/argoproj/argo-cd/v2/util/errors"
+ "github.com/argoproj/argo-cd/v2/util/git"
+ "github.com/argoproj/argo-cd/v2/util/grpc"
+ argoio "github.com/argoproj/argo-cd/v2/util/io"
+ logutils "github.com/argoproj/argo-cd/v2/util/log"
+ "github.com/argoproj/argo-cd/v2/util/manifeststream"
+ "github.com/argoproj/argo-cd/v2/util/templates"
+ "github.com/argoproj/argo-cd/v2/util/text/label"
)
// NewApplicationCommand returns a new instance of an `argocd app` command
@@ -144,7 +143,7 @@ func NewApplicationCreateCommand(clientOpts *argocdclient.ClientOptions) *cobra.
argocd app create nginx-ingress --repo https://charts.helm.sh/stable --helm-chart nginx-ingress --revision 1.24.3 --dest-namespace default --dest-server https://kubernetes.default.svc
# Create a Kustomize app
- argocd app create kustomize-guestbook --repo https://github.com/argoproj/argocd-example-apps.git --path kustomize-guestbook --dest-namespace default --dest-server https://kubernetes.default.svc --kustomize-image quay.io/argoprojlabs/argocd-e2e-container:0.1
+ argocd app create kustomize-guestbook --repo https://github.com/argoproj/argocd-example-apps.git --path kustomize-guestbook --dest-namespace default --dest-server https://kubernetes.default.svc --kustomize-image gcr.io/heptio-images/ks-guestbook-demo:0.1
# Create a MultiSource app while yaml file contains an application with multiple sources
argocd app create guestbook --file
@@ -170,7 +169,7 @@ func NewApplicationCreateCommand(clientOpts *argocdclient.ClientOptions) *cobra.
app.Finalizers = append(app.Finalizers, "resources-finalizer.argocd.argoproj.io")
}
conn, appIf := argocdClient.NewApplicationClientOrDie()
- defer utilio.Close(conn)
+ defer argoio.Close(conn)
appCreateRequest := application.ApplicationCreateRequest{
Application: app,
Upsert: &upsert,
@@ -189,16 +188,15 @@ func NewApplicationCreateCommand(clientOpts *argocdclient.ClientOptions) *cobra.
errors.CheckError(err)
var action string
- switch {
- case existing == nil:
+ if existing == nil {
action = "created"
- case !hasAppChanged(existing, created, upsert):
+ } else if !hasAppChanged(existing, created, upsert) {
action = "unchanged"
- default:
+ } else {
action = "updated"
}
- fmt.Printf("application '%s' %s\n", created.Name, action)
+ fmt.Printf("application '%s' %s\n", created.ObjectMeta.Name, action)
}
},
}
@@ -268,7 +266,7 @@ func hasAppChanged(appReq, appRes *argoappv1.Application, upsert bool) bool {
if reflect.DeepEqual(appRes.Spec, appReq.Spec) &&
reflect.DeepEqual(appRes.Labels, appReq.Labels) &&
- reflect.DeepEqual(appRes.Annotations, appReq.Annotations) &&
+ reflect.DeepEqual(appRes.ObjectMeta.Annotations, appReq.Annotations) &&
reflect.DeepEqual(appRes.Finalizers, appReq.Finalizers) {
return false
}
@@ -276,8 +274,8 @@ func hasAppChanged(appReq, appRes *argoappv1.Application, upsert bool) bool {
return true
}
-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)
+func parentChildDetails(appIf application.ApplicationServiceClient, ctx context.Context, 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{})
@@ -285,7 +283,7 @@ func parentChildDetails(ctx context.Context, appIf application.ApplicationServic
errors.CheckError(err)
for _, node := range resourceTree.Nodes {
- mapUIDToNode[node.UID] = node
+ mapUidToNode[node.UID] = node
if len(node.ParentRefs) > 0 {
_, ok := mapParentToChild[node.ParentRefs[0].UID]
@@ -298,12 +296,12 @@ func parentChildDetails(ctx context.Context, appIf application.ApplicationServic
parentNode[node.UID] = struct{}{}
}
}
- return mapUIDToNode, mapParentToChild, parentNode
+ return mapUidToNode, mapParentToChild, parentNode
}
-func printHeader(ctx context.Context, acdClient argocdclient.Client, app *argoappv1.Application, windows *argoappv1.SyncWindows, showOperation bool, showParams bool, sourcePosition int) {
- appURL := getAppURL(ctx, acdClient, app.Name)
- printAppSummaryTable(app, appURL, windows)
+func printHeader(acdClient argocdclient.Client, app *argoappv1.Application, ctx context.Context, windows *argoappv1.SyncWindows, showOperation bool, showParams bool, sourcePosition int) {
+ aURL := appURL(ctx, acdClient, app.Name)
+ printAppSummaryTable(app, aURL, windows)
if len(app.Status.Conditions) > 0 {
fmt.Println()
@@ -338,7 +336,6 @@ func NewApplicationGetCommand(clientOpts *argocdclient.ClientOptions) *cobra.Com
refresh bool
hardRefresh bool
output string
- timeout uint
showParams bool
showOperation bool
appNamespace string
@@ -384,91 +381,49 @@ func NewApplicationGetCommand(clientOpts *argocdclient.ClientOptions) *cobra.Com
`),
Run: func(c *cobra.Command, args []string) {
- ctx, cancel := context.WithCancel(c.Context())
- defer cancel()
+ ctx := c.Context()
if len(args) == 0 {
c.HelpFunc()(c, args)
os.Exit(1)
}
acdClient := headless.NewClientOrDie(clientOpts, c)
conn, appIf := acdClient.NewApplicationClientOrDie()
- defer utilio.Close(conn)
+ defer argoio.Close(conn)
appName, appNs := argo.ParseFromQualifiedName(args[0], appNamespace)
- if timeout != 0 {
- time.AfterFunc(time.Duration(timeout)*time.Second, func() {
- if ctx.Err() != nil {
- fmt.Println("Timeout function: context already cancelled:", ctx.Err())
- } else {
- fmt.Println("Timeout function: cancelling context manually")
- cancel()
- }
- })
- }
- getAppStateWithRetry := func() (*argoappv1.Application, error) {
- type getResponse struct {
- app *argoappv1.Application
- err error
- }
-
- ch := make(chan getResponse, 1)
-
- go func() {
- app, err := appIf.Get(ctx, &application.ApplicationQuery{
- Name: &appName,
- Refresh: getRefreshType(refresh, hardRefresh),
- AppNamespace: &appNs,
- })
- ch <- getResponse{app: app, err: err}
- }()
-
- select {
- case result := <-ch:
- return result.app, result.err
- case <-ctx.Done():
- // Timeout occurred, try again without refresh flag
- // Create new context for retry request
- ctx := context.Background()
- app, err := appIf.Get(ctx, &application.ApplicationQuery{
- Name: &appName,
- AppNamespace: &appNs,
- })
- return app, err
- }
- }
-
- app, err := getAppStateWithRetry()
+ app, err := appIf.Get(ctx, &application.ApplicationQuery{
+ Name: &appName,
+ Refresh: getRefreshType(refresh, hardRefresh),
+ AppNamespace: &appNs,
+ })
errors.CheckError(err)
- if ctx.Err() != nil {
- ctx = context.Background() // Reset context for subsequent requests
- }
if sourceName != "" && sourcePosition != -1 {
- errors.Fatal(errors.ErrorGeneric, "Only one of source-position and source-name can be specified.")
+ errors.CheckError(fmt.Errorf("Only one of source-position and source-name can be specified."))
}
if sourceName != "" {
sourceNameToPosition := getSourceNameToPositionMap(app)
- pos, ok := sourceNameToPosition[sourceName]
- if !ok {
+ if pos, ok := sourceNameToPosition[sourceName]; !ok {
log.Fatalf("Unknown source name '%s'", sourceName)
+ } else {
+ sourcePosition = int(pos)
}
- sourcePosition = int(pos)
}
// check for source position if --show-params is set
if app.Spec.HasMultipleSources() && showParams {
if sourcePosition <= 0 {
- errors.Fatal(errors.ErrorGeneric, "Source position should be specified and must be greater than 0 for applications with multiple sources")
+ errors.CheckError(fmt.Errorf("Source position should be specified and must be greater than 0 for applications with multiple sources"))
}
if len(app.Spec.GetSources()) < sourcePosition {
- errors.Fatal(errors.ErrorGeneric, "Source position should be less than the number of sources in the application")
+ errors.CheckError(fmt.Errorf("Source position should be less than the number of sources in the application"))
}
}
pConn, projIf := headless.NewClientOrDie(clientOpts, c).NewProjectClientOrDie()
- defer utilio.Close(pConn)
+ defer argoio.Close(pConn)
proj, err := projIf.Get(ctx, &projectpkg.ProjectQuery{Name: app.Spec.Project})
errors.CheckError(err)
@@ -479,7 +434,7 @@ func NewApplicationGetCommand(clientOpts *argocdclient.ClientOptions) *cobra.Com
err := PrintResource(app, output)
errors.CheckError(err)
case "wide", "":
- printHeader(ctx, acdClient, app, windows, showOperation, showParams, sourcePosition)
+ printHeader(acdClient, app, ctx, windows, showOperation, showParams, sourcePosition)
if len(app.Status.Resources) > 0 {
fmt.Println()
w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
@@ -487,18 +442,18 @@ func NewApplicationGetCommand(clientOpts *argocdclient.ClientOptions) *cobra.Com
_ = w.Flush()
}
case "tree":
- printHeader(ctx, acdClient, app, windows, showOperation, showParams, sourcePosition)
- mapUIDToNode, mapParentToChild, parentNode, mapNodeNameToResourceState := resourceParentChild(ctx, acdClient, appName, appNs)
- if len(mapUIDToNode) > 0 {
+ printHeader(acdClient, app, ctx, windows, showOperation, showParams, sourcePosition)
+ mapUidToNode, mapParentToChild, parentNode, mapNodeNameToResourceState := resourceParentChild(ctx, acdClient, appName, appNs)
+ if len(mapUidToNode) > 0 {
fmt.Println()
- printTreeView(mapUIDToNode, mapParentToChild, parentNode, mapNodeNameToResourceState)
+ printTreeView(mapUidToNode, mapParentToChild, parentNode, mapNodeNameToResourceState)
}
case "tree=detailed":
- printHeader(ctx, acdClient, app, windows, showOperation, showParams, sourcePosition)
- mapUIDToNode, mapParentToChild, parentNode, mapNodeNameToResourceState := resourceParentChild(ctx, acdClient, appName, appNs)
- if len(mapUIDToNode) > 0 {
+ printHeader(acdClient, app, ctx, windows, showOperation, showParams, sourcePosition)
+ mapUidToNode, mapParentToChild, parentNode, mapNodeNameToResourceState := resourceParentChild(ctx, acdClient, appName, appNs)
+ if len(mapUidToNode) > 0 {
fmt.Println()
- printTreeViewDetailed(mapUIDToNode, mapParentToChild, parentNode, mapNodeNameToResourceState)
+ printTreeViewDetailed(mapUidToNode, mapParentToChild, parentNode, mapNodeNameToResourceState)
}
default:
errors.CheckError(fmt.Errorf("unknown output format: %s", output))
@@ -506,7 +461,6 @@ func NewApplicationGetCommand(clientOpts *argocdclient.ClientOptions) *cobra.Com
},
}
command.Flags().StringVarP(&output, "output", "o", "wide", "Output format. One of: json|yaml|wide|tree")
- command.Flags().UintVar(&timeout, "timeout", defaultCheckTimeoutSeconds, "Time out after this many seconds")
command.Flags().BoolVar(&showOperation, "show-operation", false, "Show application operation")
command.Flags().BoolVar(&showParams, "show-params", false, "Show application parameters and overrides")
command.Flags().BoolVar(&refresh, "refresh", false, "Refresh application data when retrieving")
@@ -531,7 +485,6 @@ func NewApplicationLogsCommand(clientOpts *argocdclient.ClientOptions) *cobra.Co
filter string
container string
previous bool
- matchCase bool
)
command := &cobra.Command{
Use: "logs APPNAME",
@@ -567,9 +520,6 @@ func NewApplicationLogsCommand(clientOpts *argocdclient.ClientOptions) *cobra.Co
# Filter logs to show only those containing a specific string
argocd app logs my-app --filter "error"
- # Filter logs to show only those containing a specific string and match case
- argocd app logs my-app --filter "error" --match-case
-
# Get logs for a specific container within the pods
argocd app logs my-app -c my-container
@@ -586,7 +536,7 @@ func NewApplicationLogsCommand(clientOpts *argocdclient.ClientOptions) *cobra.Co
}
acdClient := headless.NewClientOrDie(clientOpts, c)
conn, appIf := acdClient.NewApplicationClientOrDie()
- defer utilio.Close(conn)
+ defer argoio.Close(conn)
appName, appNs := argo.ParseFromQualifiedName(args[0], "")
retry := true
@@ -603,7 +553,6 @@ func NewApplicationLogsCommand(clientOpts *argocdclient.ClientOptions) *cobra.Co
SinceSeconds: ptr.To(sinceSeconds),
UntilTime: &untilTime,
Filter: &filter,
- MatchCase: ptr.To(matchCase),
Container: ptr.To(container),
Previous: ptr.To(previous),
AppNamespace: &appNs,
@@ -614,7 +563,7 @@ func NewApplicationLogsCommand(clientOpts *argocdclient.ClientOptions) *cobra.Co
for {
msg, err := stream.Recv()
if err != nil {
- if stderrors.Is(err, io.EOF) {
+ if std_errors.Is(err, io.EOF) {
return
}
st, ok := status.FromError(err)
@@ -628,10 +577,11 @@ func NewApplicationLogsCommand(clientOpts *argocdclient.ClientOptions) *cobra.Co
}
log.Fatalf("stream read failed: %v", err)
}
- if msg.GetLast() {
+ if !msg.GetLast() {
+ fmt.Println(msg.GetContent())
+ } else {
return
}
- fmt.Println(msg.GetContent())
} // Done with receive message
} // Done with retry
},
@@ -648,7 +598,6 @@ func NewApplicationLogsCommand(clientOpts *argocdclient.ClientOptions) *cobra.Co
command.Flags().StringVar(&filter, "filter", "", "Show logs contain this string")
command.Flags().StringVarP(&container, "container", "c", "", "Optional container name")
command.Flags().BoolVarP(&previous, "previous", "p", false, "Specify if the previously terminated container logs should be returned")
- command.Flags().BoolVarP(&matchCase, "match-case", "m", false, "Specify if the filter should be case-sensitive")
return command
}
@@ -709,7 +658,7 @@ func printAppSummaryTable(app *argoappv1.Application, appURL string, windows *ar
}
var syncPolicy string
- if app.Spec.SyncPolicy != nil && app.Spec.SyncPolicy.IsAutomatedSyncEnabled() {
+ if app.Spec.SyncPolicy != nil && app.Spec.SyncPolicy.Automated != nil {
syncPolicy = "Automated"
if app.Spec.SyncPolicy.Automated.Prune {
syncPolicy += " (Prune)"
@@ -721,15 +670,18 @@ func printAppSummaryTable(app *argoappv1.Application, appURL string, windows *ar
syncStatusStr := string(app.Status.Sync.Status)
switch app.Status.Sync.Status {
case argoappv1.SyncStatusCodeSynced:
- syncStatusStr += " to " + app.Spec.GetSource().TargetRevision
+ syncStatusStr += fmt.Sprintf(" to %s", app.Spec.GetSource().TargetRevision)
case argoappv1.SyncStatusCodeOutOfSync:
- syncStatusStr += " from " + app.Spec.GetSource().TargetRevision
+ syncStatusStr += fmt.Sprintf(" from %s", app.Spec.GetSource().TargetRevision)
}
if !git.IsCommitSHA(app.Spec.GetSource().TargetRevision) && !git.IsTruncatedCommitSHA(app.Spec.GetSource().TargetRevision) && len(app.Status.Sync.Revision) > 7 {
syncStatusStr += fmt.Sprintf(" (%s)", app.Status.Sync.Revision[0:7])
}
fmt.Printf(printOpFmtStr, "Sync Status:", syncStatusStr)
healthStr := string(app.Status.Health.Status)
+ if app.Status.Health.Message != "" {
+ healthStr = fmt.Sprintf("%s (%s)", app.Status.Health.Status, app.Status.Health.Message)
+ }
fmt.Printf(printOpFmtStr, "Health Status:", healthStr)
}
@@ -773,10 +725,10 @@ func appURLDefault(acdClient argocdclient.Client, appName string) string {
return fmt.Sprintf("%s://%s/applications/%s", scheme, server, appName)
}
-// getAppURL returns the URL of an application
-func getAppURL(ctx context.Context, acdClient argocdclient.Client, appName string) string {
+// appURL returns the URL of an application
+func appURL(ctx context.Context, acdClient argocdclient.Client, appName string) string {
conn, settingsIf := acdClient.NewSettingsClientOrDie()
- defer utilio.Close(conn)
+ defer argoio.Close(conn)
argoSettings, err := settingsIf.Get(ctx, &settings.SettingsQuery{})
errors.CheckError(err)
@@ -877,30 +829,30 @@ func NewApplicationSetCommand(clientOpts *argocdclient.ClientOptions) *cobra.Com
appName, appNs := argo.ParseFromQualifiedName(args[0], appNamespace)
argocdClient := headless.NewClientOrDie(clientOpts, c)
conn, appIf := argocdClient.NewApplicationClientOrDie()
- defer utilio.Close(conn)
+ defer argoio.Close(conn)
app, err := appIf.Get(ctx, &application.ApplicationQuery{Name: &appName, AppNamespace: &appNs})
errors.CheckError(err)
sourceName = appOpts.SourceName
if sourceName != "" && sourcePosition != -1 {
- errors.Fatal(errors.ErrorGeneric, "Only one of source-position and source-name can be specified.")
+ errors.CheckError(fmt.Errorf("Only one of source-position and source-name can be specified."))
}
if sourceName != "" {
sourceNameToPosition := getSourceNameToPositionMap(app)
- pos, ok := sourceNameToPosition[sourceName]
- if !ok {
+ if pos, ok := sourceNameToPosition[sourceName]; !ok {
log.Fatalf("Unknown source name '%s'", sourceName)
+ } else {
+ sourcePosition = int(pos)
}
- sourcePosition = int(pos)
}
if app.Spec.HasMultipleSources() {
if sourcePosition <= 0 {
- errors.Fatal(errors.ErrorGeneric, "Source position should be specified and must be greater than 0 for applications with multiple sources")
+ errors.CheckError(fmt.Errorf("Source position should be specified and must be greater than 0 for applications with multiple sources"))
}
if len(app.Spec.GetSources()) < sourcePosition {
- errors.Fatal(errors.ErrorGeneric, "Source position should be less than the number of sources in the application")
+ errors.CheckError(fmt.Errorf("Source position should be less than the number of sources in the application"))
}
}
@@ -935,7 +887,6 @@ type unsetOpts struct {
kustomizeNamespace bool
kustomizeImages []string
kustomizeReplicas []string
- ignoreMissingComponents bool
parameters []string
valuesFiles []string
valuesLiteral bool
@@ -952,7 +903,6 @@ func (o *unsetOpts) KustomizeIsZero() bool {
!o.nameSuffix &&
!o.kustomizeVersion &&
!o.kustomizeNamespace &&
- !o.ignoreMissingComponents &&
len(o.kustomizeImages) == 0 &&
len(o.kustomizeReplicas) == 0
}
@@ -992,30 +942,30 @@ func NewApplicationUnsetCommand(clientOpts *argocdclient.ClientOptions) *cobra.C
appName, appNs := argo.ParseFromQualifiedName(args[0], appNamespace)
conn, appIf := headless.NewClientOrDie(clientOpts, c).NewApplicationClientOrDie()
- defer utilio.Close(conn)
+ defer argoio.Close(conn)
app, err := appIf.Get(ctx, &application.ApplicationQuery{Name: &appName, AppNamespace: &appNs})
errors.CheckError(err)
sourceName = appOpts.SourceName
if sourceName != "" && sourcePosition != -1 {
- errors.Fatal(errors.ErrorGeneric, "Only one of source-position and source-name can be specified.")
+ errors.CheckError(fmt.Errorf("Only one of source-position and source-name can be specified."))
}
if sourceName != "" {
sourceNameToPosition := getSourceNameToPositionMap(app)
- pos, ok := sourceNameToPosition[sourceName]
- if !ok {
+ if pos, ok := sourceNameToPosition[sourceName]; !ok {
log.Fatalf("Unknown source name '%s'", sourceName)
+ } else {
+ sourcePosition = int(pos)
}
- sourcePosition = int(pos)
}
if app.Spec.HasMultipleSources() {
if sourcePosition <= 0 {
- errors.Fatal(errors.ErrorGeneric, "Source position should be specified and must be greater than 0 for applications with multiple sources")
+ errors.CheckError(fmt.Errorf("Source position should be specified and must be greater than 0 for applications with multiple sources"))
}
if len(app.Spec.GetSources()) < sourcePosition {
- errors.Fatal(errors.ErrorGeneric, "Source position should be less than the number of sources in the application")
+ errors.CheckError(fmt.Errorf("Source position should be less than the number of sources in the application"))
}
}
@@ -1058,7 +1008,6 @@ func NewApplicationUnsetCommand(clientOpts *argocdclient.ClientOptions) *cobra.C
command.Flags().BoolVar(&opts.kustomizeNamespace, "kustomize-namespace", false, "Kustomize namespace")
command.Flags().StringArrayVar(&opts.kustomizeImages, "kustomize-image", []string{}, "Kustomize images name (e.g. --kustomize-image node --kustomize-image mysql)")
command.Flags().StringArrayVar(&opts.kustomizeReplicas, "kustomize-replica", []string{}, "Kustomize replicas name (e.g. --kustomize-replica my-deployment --kustomize-replica my-statefulset)")
- command.Flags().BoolVar(&opts.ignoreMissingComponents, "ignore-missing-components", false, "Unset the kustomize ignore-missing-components option (revert to false)")
command.Flags().StringArrayVar(&opts.pluginEnvs, "plugin-env", []string{}, "Unset plugin env variables (e.g --plugin-env name)")
command.Flags().BoolVar(&opts.passCredentials, "pass-credentials", false, "Unset passCredentials")
command.Flags().BoolVar(&opts.ref, "ref", false, "Unset ref on the source")
@@ -1099,11 +1048,6 @@ func unset(source *argoappv1.ApplicationSource, opts unsetOpts) (updated bool, n
source.Kustomize.Namespace = ""
}
- if opts.ignoreMissingComponents && source.Kustomize.IgnoreMissingComponents {
- source.Kustomize.IgnoreMissingComponents = false
- updated = true
- }
-
for _, kustomizeImage := range opts.kustomizeImages {
for i, item := range source.Kustomize.Images {
if argoappv1.KustomizeImage(kustomizeImage).Match(item) {
@@ -1256,7 +1200,7 @@ func groupObjsByKey(localObs []*unstructured.Unstructured, liveObjs []*unstructu
objByKey := make(map[kube.ResourceKey]*unstructured.Unstructured)
for i := range localObs {
obj := localObs[i]
- if !hook.IsHook(obj) && !ignore.Ignore(obj) {
+ if !(hook.IsHook(obj) || ignore.Ignore(obj)) {
objByKey[kube.GetResourceKey(obj)] = obj
}
}
@@ -1301,20 +1245,20 @@ func NewApplicationDiffCommand(clientOpts *argocdclient.ClientOptions) *cobra.Co
}
if len(sourceNames) > 0 && len(sourcePositions) > 0 {
- errors.Fatal(errors.ErrorGeneric, "Only one of source-positions and source-names can be specified.")
+ errors.CheckError(fmt.Errorf("Only one of source-positions and source-names can be specified."))
}
if len(sourcePositions) > 0 && len(revisions) != len(sourcePositions) {
- errors.Fatal(errors.ErrorGeneric, "While using --revisions and --source-positions, length of values for both flags should be same.")
+ errors.CheckError(fmt.Errorf("While using --revisions and --source-positions, length of values for both flags should be same."))
}
if len(sourceNames) > 0 && len(revisions) != len(sourceNames) {
- errors.Fatal(errors.ErrorGeneric, "While using --revisions and --source-names, length of values for both flags should be same.")
+ errors.CheckError(fmt.Errorf("While using --revisions and --source-names, length of values for both flags should be same."))
}
clientset := headless.NewClientOrDie(clientOpts, c)
conn, appIf := clientset.NewApplicationClientOrDie()
- defer utilio.Close(conn)
+ defer argoio.Close(conn)
appName, appNs := argo.ParseFromQualifiedName(args[0], appNamespace)
app, err := appIf.Get(ctx, &application.ApplicationQuery{
Name: &appName,
@@ -1327,23 +1271,22 @@ func NewApplicationDiffCommand(clientOpts *argocdclient.ClientOptions) *cobra.Co
sourceNameToPosition := getSourceNameToPositionMap(app)
for _, name := range sourceNames {
- pos, ok := sourceNameToPosition[name]
- if !ok {
+ if pos, ok := sourceNameToPosition[name]; !ok {
log.Fatalf("Unknown source name '%s'", name)
+ } else {
+ sourcePositions = append(sourcePositions, pos)
}
- sourcePositions = append(sourcePositions, pos)
}
}
resources, err := appIf.ManagedResources(ctx, &application.ResourcesQuery{ApplicationName: &appName, AppNamespace: &appNs})
errors.CheckError(err)
conn, settingsIf := clientset.NewSettingsClientOrDie()
- defer utilio.Close(conn)
+ defer argoio.Close(conn)
argoSettings, err := settingsIf.Get(ctx, &settings.SettingsQuery{})
errors.CheckError(err)
diffOption := &DifferenceOption{}
- switch {
- case app.Spec.HasMultipleSources() && len(revisions) > 0 && len(sourcePositions) > 0:
+ if app.Spec.HasMultipleSources() && len(revisions) > 0 && len(sourcePositions) > 0 {
numOfSources := int64(len(app.Spec.GetSources()))
for _, pos := range sourcePositions {
if pos <= 0 || pos > numOfSources {
@@ -1363,7 +1306,7 @@ func NewApplicationDiffCommand(clientOpts *argocdclient.ClientOptions) *cobra.Co
diffOption.res = res
diffOption.revisions = revisions
diffOption.sourcePositions = sourcePositions
- case revision != "":
+ } else if revision != "" {
q := application.ApplicationManifestQuery{
Name: &appName,
Revision: &revision,
@@ -1373,7 +1316,7 @@ func NewApplicationDiffCommand(clientOpts *argocdclient.ClientOptions) *cobra.Co
errors.CheckError(err)
diffOption.res = res
diffOption.revision = revision
- case local != "":
+ } else if local != "" {
if serverSideGenerate {
client, err := appIf.GetManifestsWithFiles(ctx, grpc_retry.Disable())
errors.CheckError(err)
@@ -1388,7 +1331,7 @@ func NewApplicationDiffCommand(clientOpts *argocdclient.ClientOptions) *cobra.Co
} else {
fmt.Fprintf(os.Stderr, "Warning: local diff without --server-side-generate is deprecated and does not work with plugins. Server-side generation will be the default in v2.7.")
conn, clusterIf := clientset.NewClusterClientOrDie()
- defer utilio.Close(conn)
+ defer argoio.Close(conn)
cluster, err := clusterIf.Get(ctx, &clusterpkg.ClusterQuery{Name: app.Spec.Destination.Name, Server: app.Spec.Destination.Server})
errors.CheckError(err)
@@ -1397,7 +1340,7 @@ func NewApplicationDiffCommand(clientOpts *argocdclient.ClientOptions) *cobra.Co
diffOption.cluster = cluster
}
}
- proj := getProject(ctx, c, clientOpts, app.Spec.Project)
+ proj := getProject(c, clientOpts, ctx, app.Spec.Project)
foundDiffs := findandPrintDiff(ctx, app, proj.Project, resources, argoSettings, diffOption, ignoreNormalizerOpts)
if foundDiffs && exitCode {
os.Exit(diffExitCode)
@@ -1439,11 +1382,10 @@ func findandPrintDiff(ctx context.Context, app *argoappv1.Application, proj *arg
liveObjs, err := cmdutil.LiveObjects(resources.Items)
errors.CheckError(err)
items := make([]objKeyLiveTarget, 0)
- switch {
- case diffOptions.local != "":
+ if diffOptions.local != "" {
localObjs := groupObjsByKey(getLocalObjects(ctx, app, proj, diffOptions.local, diffOptions.localRepoRoot, argoSettings.AppLabelKey, diffOptions.cluster.Info.ServerVersion, diffOptions.cluster.Info.APIVersions, argoSettings.KustomizeOptions, argoSettings.TrackingMethod), liveObjs, app.Spec.Destination.Namespace)
items = groupObjsForDiff(resources, localObjs, items, argoSettings, app.InstanceName(argoSettings.ControllerNamespace), app.Spec.Destination.Namespace)
- case diffOptions.revision != "" || len(diffOptions.revisions) > 0:
+ } else if diffOptions.revision != "" || len(diffOptions.revisions) > 0 {
var unstructureds []*unstructured.Unstructured
for _, mfst := range diffOptions.res.Manifests {
obj, err := argoappv1.UnmarshalToUnstructured(mfst)
@@ -1452,7 +1394,7 @@ func findandPrintDiff(ctx context.Context, app *argoappv1.Application, proj *arg
}
groupedObjs := groupObjsByKey(unstructureds, liveObjs, app.Spec.Destination.Namespace)
items = groupObjsForDiff(resources, groupedObjs, items, argoSettings, app.InstanceName(argoSettings.ControllerNamespace), app.Spec.Destination.Namespace)
- case diffOptions.serversideRes != nil:
+ } else if diffOptions.serversideRes != nil {
var unstructureds []*unstructured.Unstructured
for _, mfst := range diffOptions.serversideRes.Manifests {
obj, err := argoappv1.UnmarshalToUnstructured(mfst)
@@ -1461,7 +1403,7 @@ func findandPrintDiff(ctx context.Context, app *argoappv1.Application, proj *arg
}
groupedObjs := groupObjsByKey(unstructureds, liveObjs, app.Spec.Destination.Namespace)
items = groupObjsForDiff(resources, groupedObjs, items, argoSettings, app.InstanceName(argoSettings.ControllerNamespace), app.Spec.Destination.Namespace)
- default:
+ } else {
for i := range resources.Items {
res := resources.Items[i]
live := &unstructured.Unstructured{}
@@ -1589,8 +1531,8 @@ func NewApplicationDeleteCommand(clientOpts *argocdclient.ClientOptions) *cobra.
}
acdClient := headless.NewClientOrDie(clientOpts, c)
conn, appIf := acdClient.NewApplicationClientOrDie()
- defer utilio.Close(conn)
- isTerminal := isatty.IsTerminal(os.Stdout.Fd()) || isatty.IsCygwinTerminal(os.Stdout.Fd())
+ defer argoio.Close(conn)
+ var isTerminal bool = isatty.IsTerminal(os.Stdout.Fd()) || isatty.IsCygwinTerminal(os.Stdout.Fd())
promptFlag := c.Flag("yes")
if promptFlag.Changed && promptFlag.Value.String() == "true" {
noPrompt = true
@@ -1673,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 := []any{"NAME", "CLUSTER", "NAMESPACE", "PROJECT", "STATUS", "HEALTH", "SYNCPOLICY", "CONDITIONS"}
+ headers := []interface{}{"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")
@@ -1682,7 +1624,7 @@ func printApplicationTable(apps []argoappv1.Application, output *string) {
}
_, _ = fmt.Fprintf(w, fmtStr, headers...)
for _, app := range apps {
- vals := []any{
+ vals := []interface{}{
app.QualifiedName(),
getServer(&app),
app.Spec.Destination.Namespace,
@@ -1722,11 +1664,11 @@ 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, _ []string) {
+ Run: func(c *cobra.Command, args []string) {
ctx := c.Context()
conn, appIf := headless.NewClientOrDie(clientOpts, c).NewApplicationClientOrDie()
- defer utilio.Close(conn)
+ defer argoio.Close(conn)
apps, err := appIf.List(ctx, &application.ApplicationQuery{
Selector: ptr.To(selector),
AppNamespace: &appNamespace,
@@ -1768,7 +1710,7 @@ func NewApplicationListCommand(clientOpts *argocdclient.ClientOptions) *cobra.Co
}
func formatSyncPolicy(app argoappv1.Application) string {
- if app.Spec.SyncPolicy == nil || !app.Spec.SyncPolicy.IsAutomatedSyncEnabled() {
+ if app.Spec.SyncPolicy == nil || app.Spec.SyncPolicy.Automated == nil {
return "Manual"
}
policy := "Auto"
@@ -1796,10 +1738,6 @@ func formatConditionsSummary(app argoappv1.Application) string {
items = append(items, cndType)
}
}
-
- // Sort the keys by name
- sort.Strings(items)
-
summary := ""
if len(items) > 0 {
slices.Sort(items)
@@ -1825,7 +1763,7 @@ func parseSelectedResources(resources []string) ([]*argoappv1.SyncOperationResou
}
nameFields := strings.Split(resourceName, resourceFieldNamespaceDelimiter)
if len(nameFields) != resourceFieldNameWithNamespaceCount {
- return "", "", fmt.Errorf("resource with namespace should have GROUP%sKIND%sNAMESPACE%sNAME, but instead got: %s", resourceFieldDelimiter, resourceFieldDelimiter, resourceFieldNamespaceDelimiter, resource)
+ return "", "", fmt.Errorf("Resource with namespace should have GROUP%sKIND%sNAMESPACE%sNAME, but instead got: %s", resourceFieldDelimiter, resourceFieldDelimiter, resourceFieldNamespaceDelimiter, resource)
}
namespace := nameFields[0]
name := nameFields[1]
@@ -1846,7 +1784,7 @@ func parseSelectedResources(resources []string) ([]*argoappv1.SyncOperationResou
}
fields := strings.Split(resource, resourceFieldDelimiter)
if len(fields) != resourceFieldCount {
- return nil, fmt.Errorf("resource should have GROUP%sKIND%sNAME, but instead got: %s", resourceFieldDelimiter, resourceFieldDelimiter, resource)
+ return nil, fmt.Errorf("Resource should have GROUP%sKIND%sNAME, but instead got: %s", resourceFieldDelimiter, resourceFieldDelimiter, resource)
}
name, namespace, err := nameRetriever(fields[2], resource)
if err != nil {
@@ -1923,7 +1861,7 @@ func NewApplicationWaitCommand(clientOpts *argocdclient.ClientOptions) *cobra.Co
appNames := args
acdClient := headless.NewClientOrDie(clientOpts, c)
closer, appIf := acdClient.NewApplicationClientOrDie()
- defer utilio.Close(closer)
+ defer argoio.Close(closer)
if selector != "" {
list, err := appIf.List(ctx, &application.ApplicationQuery{Selector: ptr.To(selector)})
errors.CheckError(err)
@@ -2082,7 +2020,7 @@ func NewApplicationSyncCommand(clientOpts *argocdclient.ClientOptions) *cobra.Co
acdClient := headless.NewClientOrDie(clientOpts, c)
conn, appIf := acdClient.NewApplicationClientOrDie()
- defer utilio.Close(conn)
+ defer argoio.Close(conn)
selectedLabels, err := label.Parse(labels)
errors.CheckError(err)
@@ -2095,11 +2033,11 @@ func NewApplicationSyncCommand(clientOpts *argocdclient.ClientOptions) *cobra.Co
sourceNameToPosition := getSourceNameToPositionMap(app)
for _, name := range sourceNames {
- pos, ok := sourceNameToPosition[name]
- if !ok {
+ if pos, ok := sourceNameToPosition[name]; !ok {
log.Fatalf("Unknown source name '%s'", name)
+ } else {
+ sourcePositions = append(sourcePositions, pos)
}
- sourcePositions = append(sourcePositions, pos)
}
}
@@ -2116,7 +2054,7 @@ func NewApplicationSyncCommand(clientOpts *argocdclient.ClientOptions) *cobra.Co
if len(list.Items) == 0 {
errMsg := "No matching apps found for filter:"
if selector != "" {
- errMsg += " selector " + selector
+ errMsg += fmt.Sprintf(" selector %s", selector)
}
if len(projects) != 0 {
errMsg += fmt.Sprintf(" projects %v", projects)
@@ -2204,7 +2142,7 @@ func NewApplicationSyncCommand(clientOpts *argocdclient.ClientOptions) *cobra.Co
}
if local != "" {
- if app.Spec.SyncPolicy != nil && app.Spec.SyncPolicy.IsAutomatedSyncEnabled() && !dryRun {
+ if app.Spec.SyncPolicy != nil && app.Spec.SyncPolicy.Automated != nil && !dryRun {
log.Fatal("Cannot use local sync when Automatic Sync Policy is enabled except with --dry-run")
}
@@ -2212,15 +2150,15 @@ func NewApplicationSyncCommand(clientOpts *argocdclient.ClientOptions) *cobra.Co
conn, settingsIf := acdClient.NewSettingsClientOrDie()
argoSettings, err := settingsIf.Get(ctx, &settings.SettingsQuery{})
errors.CheckError(err)
- utilio.Close(conn)
+ argoio.Close(conn)
conn, clusterIf := acdClient.NewClusterClientOrDie()
- defer utilio.Close(conn)
+ defer argoio.Close(conn)
cluster, err := clusterIf.Get(ctx, &clusterpkg.ClusterQuery{Name: app.Spec.Destination.Name, Server: app.Spec.Destination.Server})
errors.CheckError(err)
- utilio.Close(conn)
+ argoio.Close(conn)
- proj := getProject(ctx, c, clientOpts, app.Spec.Project)
+ proj := getProject(c, clientOpts, ctx, 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
@@ -2290,25 +2228,26 @@ func NewApplicationSyncCommand(clientOpts *argocdclient.ClientOptions) *cobra.Co
})
errors.CheckError(err)
conn, settingsIf := acdClient.NewSettingsClientOrDie()
- defer utilio.Close(conn)
+ defer argoio.Close(conn)
argoSettings, err := settingsIf.Get(ctx, &settings.SettingsQuery{})
errors.CheckError(err)
foundDiffs := false
fmt.Printf("====== Previewing differences between live and desired state of application %s ======\n", appQualifiedName)
- proj := getProject(ctx, c, clientOpts, app.Spec.Project)
+ proj := getProject(c, clientOpts, ctx, app.Spec.Project)
foundDiffs = findandPrintDiff(ctx, app, proj.Project, resources, argoSettings, diffOption, ignoreNormalizerOpts)
- if !foundDiffs {
+ if foundDiffs {
+ if !diffChangesConfirm {
+ yesno := cli.AskToProceed(fmt.Sprintf("Please review changes to application %s shown above. Do you want to continue the sync process? (y/n): ", appQualifiedName))
+ if !yesno {
+ os.Exit(0)
+ }
+ }
+ } else {
fmt.Printf("====== No Differences found ======\n")
// if no differences found, then no need to sync
return
}
- if !diffChangesConfirm {
- yesno := cli.AskToProceed(fmt.Sprintf("Please review changes to application %s shown above. Do you want to continue the sync process? (y/n): ", appQualifiedName))
- if !yesno {
- os.Exit(0)
- }
- }
}
_, err = appIf.Sync(ctx, &syncReq)
errors.CheckError(err)
@@ -2399,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() []any {
+func (rs *resourceState) FormatItems() []interface{} {
timeStr := time.Now().Format("2006-01-02T15:04:05-07:00")
- return []any{timeStr, rs.Group, rs.Kind, rs.Namespace, rs.Name, rs.Status, rs.Health, rs.Hook, rs.Message}
+ return []interface{}{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.
@@ -2517,21 +2456,28 @@ func checkResourceStatus(watch watchOpts, healthStatus string, syncStatus string
if watch.delete {
return false
}
-
- healthBeingChecked := watch.suspended || watch.health || watch.degraded
healthCheckPassed := true
- if healthBeingChecked {
- healthCheckPassed = false
- if watch.health {
- healthCheckPassed = healthCheckPassed || healthStatus == string(health.HealthStatusHealthy)
- }
- if watch.suspended {
- healthCheckPassed = healthCheckPassed || healthStatus == string(health.HealthStatusSuspended)
- }
- if watch.degraded {
- healthCheckPassed = healthCheckPassed || healthStatus == string(health.HealthStatusDegraded)
- }
+ if watch.suspended && watch.health && watch.degraded {
+ healthCheckPassed = healthStatus == string(health.HealthStatusHealthy) ||
+ healthStatus == string(health.HealthStatusSuspended) ||
+ healthStatus == string(health.HealthStatusDegraded)
+ } else if watch.suspended && watch.degraded {
+ healthCheckPassed = healthStatus == string(health.HealthStatusDegraded) ||
+ healthStatus == string(health.HealthStatusSuspended)
+ } else if watch.degraded && watch.health {
+ healthCheckPassed = healthStatus == string(health.HealthStatusHealthy) ||
+ healthStatus == string(health.HealthStatusDegraded)
+ // below are good
+ } else if watch.suspended && watch.health {
+ healthCheckPassed = healthStatus == string(health.HealthStatusHealthy) ||
+ healthStatus == string(health.HealthStatusSuspended)
+ } else if watch.suspended {
+ healthCheckPassed = healthStatus == string(health.HealthStatusSuspended)
+ } else if watch.health {
+ healthCheckPassed = healthStatus == string(health.HealthStatusHealthy)
+ } else if watch.degraded {
+ healthCheckPassed = healthStatus == string(health.HealthStatusDegraded)
}
synced := !watch.sync || syncStatus == string(argoappv1.SyncStatusCodeSynced)
@@ -2544,43 +2490,18 @@ 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(ctx, appIf, appName, appNs)
+ mapUidToNode, mapParentToChild, parentNode := parentChildDetails(appIf, ctx, 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)
for _, res := range getResourceStates(app, nil) {
mapNodeNameToResourceState[res.Kind+"/"+res.Name] = res
}
- return mapUIDToNode, mapParentToChild, parentNode, mapNodeNameToResourceState
+ return mapUidToNode, mapParentToChild, parentNode, mapNodeNameToResourceState
}
const waitFormatString = "%s\t%5s\t%10s\t%10s\t%20s\t%8s\t%7s\t%10s\t%s\n"
-// AppWithLock encapsulates the application and its lock
-type AppWithLock struct {
- mu sync.Mutex
- app *argoappv1.Application
-}
-
-// NewAppWithLock creates a new AppWithLock instance
-func NewAppWithLock() *AppWithLock {
- return &AppWithLock{}
-}
-
-// SetApp safely updates the application
-func (a *AppWithLock) SetApp(app *argoappv1.Application) {
- a.mu.Lock()
- defer a.mu.Unlock()
- a.app = app
-}
-
-// GetApp safely retrieves the application
-func (a *AppWithLock) GetApp() *argoappv1.Application {
- a.mu.Lock()
- defer a.mu.Unlock()
- return a.app
-}
-
// waitOnApplicationStatus watches an application and blocks until either the desired watch conditions
// are fulfilled or we reach the timeout. Returns the app once desired conditions have been filled.
// Additionally return the operationState at time of fulfilment (which may be different than returned app).
@@ -2588,15 +2509,11 @@ func waitOnApplicationStatus(ctx context.Context, acdClient argocdclient.Client,
ctx, cancel := context.WithCancel(ctx)
defer cancel()
- appWithLock := NewAppWithLock()
// refresh controls whether or not we refresh the app before printing the final status.
// We only want to do this when an operation is in progress, since operations are the only
// time when the sync status lags behind when an operation completes
refresh := false
- // appURL is declared here so that it can be used in the printFinalStatus function when the context is cancelled
- appURL := getAppURL(ctx, acdClient, appName)
-
// printSummary controls whether we print the app summary table, OperationState, and ResourceState
// We don't want to print these when output type is json or yaml, as the output would become unparsable.
printSummary := output != "json" && output != "yaml"
@@ -2619,7 +2536,7 @@ func waitOnApplicationStatus(ctx context.Context, acdClient argocdclient.Client,
if printSummary {
fmt.Println()
- printAppSummaryTable(app, appURL, nil)
+ printAppSummaryTable(app, appURL(ctx, acdClient, appName), nil)
fmt.Println()
if watch.operation {
printOperationResult(app.Status.OperationState)
@@ -2638,17 +2555,16 @@ func waitOnApplicationStatus(ctx context.Context, acdClient argocdclient.Client,
_ = w.Flush()
}
case "tree":
- mapUIDToNode, mapParentToChild, parentNode, mapNodeNameToResourceState := resourceParentChild(ctx, acdClient, appRealName, appNs)
- if len(mapUIDToNode) > 0 {
+ mapUidToNode, mapParentToChild, parentNode, mapNodeNameToResourceState := resourceParentChild(ctx, acdClient, appRealName, appNs)
+ if len(mapUidToNode) > 0 {
fmt.Println()
- printTreeView(mapUIDToNode, mapParentToChild, parentNode, mapNodeNameToResourceState)
+ printTreeView(mapUidToNode, mapParentToChild, parentNode, mapNodeNameToResourceState)
}
case "tree=detailed":
-
- mapUIDToNode, mapParentToChild, parentNode, mapNodeNameToResourceState := resourceParentChild(ctx, acdClient, appRealName, appNs)
- if len(mapUIDToNode) > 0 {
+ mapUidToNode, mapParentToChild, parentNode, mapNodeNameToResourceState := resourceParentChild(ctx, acdClient, appRealName, appNs)
+ if len(mapUidToNode) > 0 {
fmt.Println()
- printTreeViewDetailed(mapUIDToNode, mapParentToChild, parentNode, mapNodeNameToResourceState)
+ printTreeViewDetailed(mapUidToNode, mapParentToChild, parentNode, mapNodeNameToResourceState)
}
default:
errors.CheckError(fmt.Errorf("unknown output format: %s", output))
@@ -2658,24 +2574,19 @@ func waitOnApplicationStatus(ctx context.Context, acdClient argocdclient.Client,
if timeout != 0 {
time.AfterFunc(time.Duration(timeout)*time.Second, func() {
- conn, appClient := acdClient.NewApplicationClientOrDie()
- defer conn.Close()
- // We want to print the final status of the app even if the conditions are not met
- if printSummary {
- fmt.Println()
- fmt.Println("This is the state of the app after wait timed out:")
- }
- // Setting refresh = false because we don't want printFinalStatus to execute a refresh
- refresh = false
- // Updating the app object to the latest state
+ _, appClient := acdClient.NewApplicationClientOrDie()
app, err := appClient.Get(ctx, &application.ApplicationQuery{
Name: &appRealName,
AppNamespace: &appNs,
})
errors.CheckError(err)
- // Update the app object
- appWithLock.SetApp(app)
- // Cancel the context to stop the watch
+
+ if printSummary {
+ fmt.Println()
+ fmt.Println("This is the state of the app after `wait` timed out:")
+ }
+
+ printFinalStatus(app)
cancel()
if printSummary {
@@ -2692,13 +2603,12 @@ func waitOnApplicationStatus(ctx context.Context, acdClient argocdclient.Client,
prevStates := make(map[string]*resourceState)
conn, appClient := acdClient.NewApplicationClientOrDie()
- defer utilio.Close(conn)
+ defer argoio.Close(conn)
app, err := appClient.Get(ctx, &application.ApplicationQuery{
Name: &appRealName,
AppNamespace: &appNs,
})
errors.CheckError(err)
- appWithLock.SetApp(app) // Update the app object
// printFinalStatus() will refresh and update the app object, potentially causing the app's
// status.operationState to be different than the version when we break out of the event loop.
@@ -2706,12 +2616,11 @@ func waitOnApplicationStatus(ctx context.Context, acdClient argocdclient.Client,
// finalOperationState captures the operationState as it was seen when we met the conditions of
// the wait, so the caller can rely on it to determine the outcome of the operation.
// See: https://github.com/argoproj/argo-cd/issues/5592
- finalOperationState := appWithLock.GetApp().Status.OperationState
+ finalOperationState := app.Status.OperationState
- appEventCh := acdClient.WatchApplicationWithRetry(ctx, appName, appWithLock.GetApp().ResourceVersion)
+ appEventCh := acdClient.WatchApplicationWithRetry(ctx, appName, app.ResourceVersion)
for appEvent := range appEventCh {
- appWithLock.SetApp(&appEvent.Application)
- app = appWithLock.GetApp()
+ app = &appEvent.Application
finalOperationState = app.Status.OperationState
operationInProgress := false
@@ -2782,7 +2691,7 @@ func waitOnApplicationStatus(ctx context.Context, acdClient argocdclient.Client,
}
_ = w.Flush()
}
- _ = printFinalStatus(appWithLock.GetApp())
+ _ = printFinalStatus(app)
return nil, finalOperationState, fmt.Errorf("timed out (%ds) waiting for app %q match desired state", timeout, appName)
}
@@ -2822,7 +2731,7 @@ func setParameterOverrides(app *argoappv1.Application, parameters []string, sour
}
// Print list of history ID's for an application.
-func printApplicationHistoryIDs(revHistory []argoappv1.RevisionHistory) {
+func printApplicationHistoryIds(revHistory []argoappv1.RevisionHistory) {
for _, depInfo := range revHistory {
fmt.Println(depInfo.ID)
}
@@ -2830,7 +2739,7 @@ func printApplicationHistoryIDs(revHistory []argoappv1.RevisionHistory) {
// Print a history table for an application.
func printApplicationHistoryTable(revHistory []argoappv1.RevisionHistory) {
- maxAllowedRevisions := 7
+ MAX_ALLOWED_REVISIONS := 7
w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
type history struct {
id int64
@@ -2843,8 +2752,8 @@ func printApplicationHistoryTable(revHistory []argoappv1.RevisionHistory) {
if depInfo.Sources != nil {
for i, sourceInfo := range depInfo.Sources {
rev := sourceInfo.TargetRevision
- if len(depInfo.Revisions) == len(depInfo.Sources) && len(depInfo.Revisions[i]) >= maxAllowedRevisions {
- rev = fmt.Sprintf("%s (%s)", rev, depInfo.Revisions[i][0:maxAllowedRevisions])
+ if len(depInfo.Revisions) == len(depInfo.Sources) && len(depInfo.Revisions[i]) >= MAX_ALLOWED_REVISIONS {
+ rev = fmt.Sprintf("%s (%s)", rev, depInfo.Revisions[i][0:MAX_ALLOWED_REVISIONS])
}
if _, ok := varHistory[sourceInfo.RepoURL]; !ok {
varHistoryKeys = append(varHistoryKeys, sourceInfo.RepoURL)
@@ -2857,8 +2766,8 @@ func printApplicationHistoryTable(revHistory []argoappv1.RevisionHistory) {
}
} else {
rev := depInfo.Source.TargetRevision
- if len(depInfo.Revision) >= maxAllowedRevisions {
- rev = fmt.Sprintf("%s (%s)", rev, depInfo.Revision[0:maxAllowedRevisions])
+ if len(depInfo.Revision) >= MAX_ALLOWED_REVISIONS {
+ rev = fmt.Sprintf("%s (%s)", rev, depInfo.Revision[0:MAX_ALLOWED_REVISIONS])
}
if _, ok := varHistory[depInfo.Source.RepoURL]; !ok {
varHistoryKeys = append(varHistoryKeys, depInfo.Source.RepoURL)
@@ -2901,7 +2810,7 @@ func NewApplicationHistoryCommand(clientOpts *argocdclient.ClientOptions) *cobra
os.Exit(1)
}
conn, appIf := headless.NewClientOrDie(clientOpts, c).NewApplicationClientOrDie()
- defer utilio.Close(conn)
+ defer argoio.Close(conn)
appName, appNs := argo.ParseFromQualifiedName(args[0], appNamespace)
app, err := appIf.Get(ctx, &application.ApplicationQuery{
Name: &appName,
@@ -2910,7 +2819,7 @@ func NewApplicationHistoryCommand(clientOpts *argocdclient.ClientOptions) *cobra
errors.CheckError(err)
if output == "id" {
- printApplicationHistoryIDs(app.Status.History)
+ printApplicationHistoryIds(app.Status.History)
} else {
printApplicationHistoryTable(app.Status.History)
}
@@ -2926,7 +2835,7 @@ func findRevisionHistory(application *argoappv1.Application, historyId int64) (*
if historyId == -1 {
l := len(application.Status.History)
if l < 2 {
- return nil, fmt.Errorf("application '%s' should have at least two successful deployments", application.Name)
+ return nil, fmt.Errorf("Application '%s' should have at least two successful deployments", application.ObjectMeta.Name)
}
return &application.Status.History[l-2], nil
}
@@ -2935,7 +2844,7 @@ func findRevisionHistory(application *argoappv1.Application, historyId int64) (*
return &di, nil
}
}
- return nil, fmt.Errorf("application '%s' does not have deployment id '%d' in history", application.Name, historyId)
+ return nil, fmt.Errorf("Application '%s' does not have deployment id '%d' in history\n", application.ObjectMeta.Name, historyId)
}
// NewApplicationRollbackCommand returns a new instance of an `argocd app rollback` command
@@ -2964,7 +2873,7 @@ func NewApplicationRollbackCommand(clientOpts *argocdclient.ClientOptions) *cobr
}
acdClient := headless.NewClientOrDie(clientOpts, c)
conn, appIf := acdClient.NewApplicationClientOrDie()
- defer utilio.Close(conn)
+ defer argoio.Close(conn)
app, err := appIf.Get(ctx, &application.ApplicationQuery{
Name: &appName,
AppNamespace: &appNs,
@@ -3063,15 +2972,15 @@ func NewApplicationManifestsCommand(clientOpts *argocdclient.ClientOptions) *cob
}
if len(sourceNames) > 0 && len(sourcePositions) > 0 {
- errors.Fatal(errors.ErrorGeneric, "Only one of source-positions and source-names can be specified.")
+ errors.CheckError(fmt.Errorf("Only one of source-positions and source-names can be specified."))
}
if len(sourcePositions) > 0 && len(revisions) != len(sourcePositions) {
- errors.Fatal(errors.ErrorGeneric, "While using --revisions and --source-positions, length of values for both flags should be same.")
+ errors.CheckError(fmt.Errorf("While using --revisions and --source-positions, length of values for both flags should be same."))
}
if len(sourceNames) > 0 && len(revisions) != len(sourceNames) {
- errors.Fatal(errors.ErrorGeneric, "While using --revisions and --source-names, length of values for both flags should be same.")
+ errors.CheckError(fmt.Errorf("While using --revisions and --source-names, length of values for both flags should be same."))
}
for _, pos := range sourcePositions {
@@ -3083,7 +2992,7 @@ func NewApplicationManifestsCommand(clientOpts *argocdclient.ClientOptions) *cob
appName, appNs := argo.ParseFromQualifiedName(args[0], "")
clientset := headless.NewClientOrDie(clientOpts, c)
conn, appIf := clientset.NewApplicationClientOrDie()
- defer utilio.Close(conn)
+ defer argoio.Close(conn)
app, err := appIf.Get(context.Background(), &application.ApplicationQuery{
Name: &appName,
@@ -3095,11 +3004,11 @@ func NewApplicationManifestsCommand(clientOpts *argocdclient.ClientOptions) *cob
sourceNameToPosition := getSourceNameToPositionMap(app)
for _, name := range sourceNames {
- pos, ok := sourceNameToPosition[name]
- if !ok {
+ if pos, ok := sourceNameToPosition[name]; !ok {
log.Fatalf("Unknown source name '%s'", name)
+ } else {
+ sourcePositions = append(sourcePositions, pos)
}
- sourcePositions = append(sourcePositions, pos)
}
}
@@ -3112,22 +3021,21 @@ func NewApplicationManifestsCommand(clientOpts *argocdclient.ClientOptions) *cob
var unstructureds []*unstructured.Unstructured
switch source {
case "git":
- switch {
- case local != "":
+ if local != "" {
settingsConn, settingsIf := clientset.NewSettingsClientOrDie()
- defer utilio.Close(settingsConn)
+ defer argoio.Close(settingsConn)
argoSettings, err := settingsIf.Get(context.Background(), &settings.SettingsQuery{})
errors.CheckError(err)
clusterConn, clusterIf := clientset.NewClusterClientOrDie()
- defer utilio.Close(clusterConn)
+ defer argoio.Close(clusterConn)
cluster, err := clusterIf.Get(context.Background(), &clusterpkg.ClusterQuery{Name: app.Spec.Destination.Name, Server: app.Spec.Destination.Server})
errors.CheckError(err)
- proj := getProject(ctx, c, clientOpts, app.Spec.Project)
- //nolint:staticcheck
+ proj := getProject(c, clientOpts, ctx, 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)
- case len(revisions) > 0 && len(sourcePositions) > 0:
+ } else if len(revisions) > 0 && len(sourcePositions) > 0 {
q := application.ApplicationManifestQuery{
Name: &appName,
AppNamespace: &appNs,
@@ -3143,7 +3051,7 @@ func NewApplicationManifestsCommand(clientOpts *argocdclient.ClientOptions) *cob
errors.CheckError(err)
unstructureds = append(unstructureds, obj)
}
- case revision != "":
+ } else if revision != "" {
q := application.ApplicationManifestQuery{
Name: &appName,
AppNamespace: &appNs,
@@ -3157,7 +3065,7 @@ func NewApplicationManifestsCommand(clientOpts *argocdclient.ClientOptions) *cob
errors.CheckError(err)
unstructureds = append(unstructureds, obj)
}
- default:
+ } else {
targetObjs, err := targetObjects(resources.Items)
errors.CheckError(err)
unstructureds = targetObjs
@@ -3202,7 +3110,7 @@ func NewApplicationTerminateOpCommand(clientOpts *argocdclient.ClientOptions) *c
}
appName, appNs := argo.ParseFromQualifiedName(args[0], "")
conn, appIf := headless.NewClientOrDie(clientOpts, c).NewApplicationClientOrDie()
- defer utilio.Close(conn)
+ defer argoio.Close(conn)
_, err := appIf.TerminateOperation(ctx, &application.OperationTerminateRequest{
Name: &appName,
AppNamespace: &appNs,
@@ -3229,7 +3137,7 @@ func NewApplicationEditCommand(clientOpts *argocdclient.ClientOptions) *cobra.Co
appName, appNs := argo.ParseFromQualifiedName(args[0], appNamespace)
conn, appIf := headless.NewClientOrDie(clientOpts, c).NewApplicationClientOrDie()
- defer utilio.Close(conn)
+ defer argoio.Close(conn)
app, err := appIf.Get(ctx, &application.ApplicationQuery{
Name: &appName,
AppNamespace: &appNs,
@@ -3241,7 +3149,7 @@ func NewApplicationEditCommand(clientOpts *argocdclient.ClientOptions) *cobra.Co
appData, err = yaml.JSONToYAML(appData)
errors.CheckError(err)
- cli.InteractiveEdit(appName+"-*-edit.yaml", appData, func(input []byte) error {
+ cli.InteractiveEdit(fmt.Sprintf("%s-*-edit.yaml", appName), appData, func(input []byte) error {
input, err = yaml.YAMLToJSON(input)
if err != nil {
return fmt.Errorf("error converting YAML to JSON: %w", err)
@@ -3299,7 +3207,7 @@ func NewApplicationPatchCommand(clientOpts *argocdclient.ClientOptions) *cobra.C
}
appName, appNs := argo.ParseFromQualifiedName(args[0], appNamespace)
conn, appIf := headless.NewClientOrDie(clientOpts, c).NewApplicationClientOrDie()
- defer utilio.Close(conn)
+ defer argoio.Close(conn)
patchedApp, err := appIf.Patch(ctx, &application.ApplicationPatchRequest{
Name: &appName,
@@ -3341,7 +3249,7 @@ func NewApplicationAddSourceCommand(clientOpts *argocdclient.ClientOptions) *cob
argocdClient := headless.NewClientOrDie(clientOpts, c)
conn, appIf := argocdClient.NewApplicationClientOrDie()
- defer utilio.Close(conn)
+ defer argoio.Close(conn)
appName, appNs := argo.ParseFromQualifiedName(args[0], appNamespace)
@@ -3354,7 +3262,7 @@ func NewApplicationAddSourceCommand(clientOpts *argocdclient.ClientOptions) *cob
errors.CheckError(err)
if c.Flags() == nil {
- errors.Fatal(errors.ErrorGeneric, "ApplicationSource needs atleast repoUrl, path or chart or ref field. No source to add.")
+ errors.CheckError(fmt.Errorf("ApplicationSource needs atleast repoUrl, path or chart or ref field. No source to add."))
}
if len(app.Spec.Sources) > 0 {
@@ -3374,9 +3282,9 @@ func NewApplicationAddSourceCommand(clientOpts *argocdclient.ClientOptions) *cob
})
errors.CheckError(err)
- fmt.Printf("Application '%s' updated successfully\n", app.Name)
+ fmt.Printf("Application '%s' updated successfully\n", app.ObjectMeta.Name)
} else {
- errors.Fatal(errors.ErrorGeneric, fmt.Sprintf("Cannot add source: application %s does not have spec.sources defined", appName))
+ errors.CheckError(fmt.Errorf("Cannot add source: application %s does not have spec.sources defined", appName))
}
},
}
@@ -3409,12 +3317,12 @@ func NewApplicationRemoveSourceCommand(clientOpts *argocdclient.ClientOptions) *
}
if sourceName == "" && sourcePosition <= 0 {
- errors.Fatal(errors.ErrorGeneric, "Value of source-position must be greater than 0")
+ errors.CheckError(fmt.Errorf("Value of source-position must be greater than 0"))
}
argocdClient := headless.NewClientOrDie(clientOpts, c)
conn, appIf := argocdClient.NewApplicationClientOrDie()
- defer utilio.Close(conn)
+ defer argoio.Close(conn)
appName, appNs := argo.ParseFromQualifiedName(args[0], appNamespace)
@@ -3426,28 +3334,28 @@ func NewApplicationRemoveSourceCommand(clientOpts *argocdclient.ClientOptions) *
errors.CheckError(err)
if sourceName != "" && sourcePosition != -1 {
- errors.Fatal(errors.ErrorGeneric, "Only one of source-position and source-name can be specified.")
+ errors.CheckError(fmt.Errorf("Only one of source-position and source-name can be specified."))
}
if sourceName != "" {
sourceNameToPosition := getSourceNameToPositionMap(app)
- pos, ok := sourceNameToPosition[sourceName]
- if !ok {
+ if pos, ok := sourceNameToPosition[sourceName]; !ok {
log.Fatalf("Unknown source name '%s'", sourceName)
+ } else {
+ sourcePosition = int(pos)
}
- sourcePosition = int(pos)
}
if !app.Spec.HasMultipleSources() {
- errors.Fatal(errors.ErrorGeneric, "Application does not have multiple sources configured")
+ errors.CheckError(fmt.Errorf("Application does not have multiple sources configured"))
}
if len(app.Spec.GetSources()) == 1 {
- errors.Fatal(errors.ErrorGeneric, "Cannot remove the only source remaining in the app")
+ errors.CheckError(fmt.Errorf("Cannot remove the only source remaining in the app"))
}
if len(app.Spec.GetSources()) < sourcePosition {
- errors.Fatal(errors.ErrorGeneric, fmt.Sprintf("Application does not have source at %d\n", sourcePosition))
+ errors.CheckError(fmt.Errorf("Application does not have source at %d\n", sourcePosition))
}
app.Spec.Sources = append(app.Spec.Sources[:sourcePosition-1], app.Spec.Sources[sourcePosition:]...)
@@ -3462,7 +3370,7 @@ func NewApplicationRemoveSourceCommand(clientOpts *argocdclient.ClientOptions) *
})
errors.CheckError(err)
- fmt.Printf("Application '%s' updated successfully\n", app.Name)
+ fmt.Printf("Application '%s' updated successfully\n", app.ObjectMeta.Name)
} else {
fmt.Println("The command to delete the source was cancelled")
}
@@ -3489,7 +3397,7 @@ func NewApplicationConfirmDeletionCommand(clientOpts *argocdclient.ClientOptions
argocdClient := headless.NewClientOrDie(clientOpts, c)
conn, appIf := argocdClient.NewApplicationClientOrDie()
- defer utilio.Close(conn)
+ defer argoio.Close(conn)
appName, appNs := argo.ParseFromQualifiedName(args[0], appNamespace)
@@ -3514,7 +3422,7 @@ func NewApplicationConfirmDeletionCommand(clientOpts *argocdclient.ClientOptions
})
errors.CheckError(err)
- fmt.Printf("Application '%s' updated successfully\n", app.Name)
+ fmt.Printf("Application '%s' updated successfully\n", app.ObjectMeta.Name)
},
}
command.Flags().StringVarP(&appNamespace, "app-namespace", "N", "", "Namespace of the target application where the source will be appended")
diff --git a/cmd/argocd/commands/app_actions.go b/cmd/argocd/commands/app_actions.go
index b445011bae..f795585d07 100644
--- a/cmd/argocd/commands/app_actions.go
+++ b/cmd/argocd/commands/app_actions.go
@@ -8,23 +8,23 @@ import (
"strconv"
"text/tabwriter"
- "github.com/argoproj/argo-cd/v3/util/templates"
+ "github.com/argoproj/argo-cd/v2/util/templates"
- "github.com/argoproj/argo-cd/v3/cmd/util"
+ "github.com/argoproj/argo-cd/v2/cmd/util"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"k8s.io/utils/ptr"
"sigs.k8s.io/yaml"
- "github.com/argoproj/argo-cd/v3/cmd/argocd/commands/headless"
- argocdclient "github.com/argoproj/argo-cd/v3/pkg/apiclient"
- applicationpkg "github.com/argoproj/argo-cd/v3/pkg/apiclient/application"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- "github.com/argoproj/argo-cd/v3/util/argo"
- "github.com/argoproj/argo-cd/v3/util/errors"
- utilio "github.com/argoproj/argo-cd/v3/util/io"
+ "github.com/argoproj/argo-cd/v2/cmd/argocd/commands/headless"
+ 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/util/argo"
+ "github.com/argoproj/argo-cd/v2/util/errors"
+ "github.com/argoproj/argo-cd/v2/util/io"
)
type DisplayedAction struct {
@@ -83,8 +83,8 @@ func NewApplicationResourceActionsListCommand(clientOpts *argocdclient.ClientOpt
}
appName, appNs := argo.ParseFromQualifiedName(args[0], "")
conn, appIf := headless.NewClientOrDie(clientOpts, c).NewApplicationClientOrDie()
- defer utilio.Close(conn)
- resources, err := getActionableResourcesForApplication(ctx, appIf, &appNs, &appName)
+ defer io.Close(conn)
+ resources, err := getActionableResourcesForApplication(appIf, ctx, &appNs, &appName)
errors.CheckError(err)
filteredObjects, err := util.FilterResources(command.Flags().Changed("group"), resources, group, kind, namespace, resourceName, true)
errors.CheckError(err)
@@ -175,8 +175,8 @@ func NewApplicationResourceActionsRunCommand(clientOpts *argocdclient.ClientOpti
actionName := args[1]
conn, appIf := headless.NewClientOrDie(clientOpts, c).NewApplicationClientOrDie()
- defer utilio.Close(conn)
- resources, err := getActionableResourcesForApplication(ctx, appIf, &appNs, &appName)
+ defer io.Close(conn)
+ resources, err := getActionableResourcesForApplication(appIf, ctx, &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(ctx context.Context, appIf applicationpkg.ApplicationServiceClient, appNs *string, appName *string) ([]*v1alpha1.ResourceDiff, error) {
+func getActionableResourcesForApplication(appIf applicationpkg.ApplicationServiceClient, ctx context.Context, appNs *string, appName *string) ([]*v1alpha1.ResourceDiff, error) {
resources, err := appIf.ManagedResources(ctx, &applicationpkg.ResourcesQuery{
ApplicationName: appName,
AppNamespace: appNs,
diff --git a/cmd/argocd/commands/app_resource_test.go b/cmd/argocd/commands/app_resource_test.go
index 4de6e0cbf3..171da12b47 100644
--- a/cmd/argocd/commands/app_resource_test.go
+++ b/cmd/argocd/commands/app_resource_test.go
@@ -8,7 +8,7 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
)
func TestPrintTreeViewAppResources(t *testing.T) {
diff --git a/cmd/argocd/commands/app_resources.go b/cmd/argocd/commands/app_resources.go
index f2a6cd4a32..e7cc47fa8b 100644
--- a/cmd/argocd/commands/app_resources.go
+++ b/cmd/argocd/commands/app_resources.go
@@ -5,21 +5,21 @@ import (
"os"
"text/tabwriter"
- "github.com/argoproj/argo-cd/v3/cmd/argocd/commands/utils"
- "github.com/argoproj/argo-cd/v3/cmd/util"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/cmd/argocd/commands/utils"
+ "github.com/argoproj/argo-cd/v2/cmd/util"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"k8s.io/apimachinery/pkg/types"
"k8s.io/utils/ptr"
- "github.com/argoproj/argo-cd/v3/cmd/argocd/commands/headless"
- argocdclient "github.com/argoproj/argo-cd/v3/pkg/apiclient"
- applicationpkg "github.com/argoproj/argo-cd/v3/pkg/apiclient/application"
- "github.com/argoproj/argo-cd/v3/util/argo"
- "github.com/argoproj/argo-cd/v3/util/errors"
- utilio "github.com/argoproj/argo-cd/v3/util/io"
+ "github.com/argoproj/argo-cd/v2/cmd/argocd/commands/headless"
+ 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/util/argo"
+ "github.com/argoproj/argo-cd/v2/util/errors"
+ argoio "github.com/argoproj/argo-cd/v2/util/io"
)
func NewApplicationPatchResourceCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command {
@@ -58,7 +58,7 @@ func NewApplicationPatchResourceCommand(clientOpts *argocdclient.ClientOptions)
appName, appNs := argo.ParseFromQualifiedName(args[0], "")
conn, appIf := headless.NewClientOrDie(clientOpts, c).NewApplicationClientOrDie()
- defer utilio.Close(conn)
+ defer argoio.Close(conn)
resources, err := appIf.ManagedResources(ctx, &applicationpkg.ResourcesQuery{
ApplicationName: &appName,
AppNamespace: &appNs,
@@ -123,7 +123,7 @@ func NewApplicationDeleteResourceCommand(clientOpts *argocdclient.ClientOptions)
appName, appNs := argo.ParseFromQualifiedName(args[0], "")
conn, appIf := headless.NewClientOrDie(clientOpts, c).NewApplicationClientOrDie()
- defer utilio.Close(conn)
+ defer argoio.Close(conn)
resources, err := appIf.ManagedResources(ctx, &applicationpkg.ResourcesQuery{
ApplicationName: &appName,
AppNamespace: &appNs,
@@ -164,12 +164,12 @@ func NewApplicationDeleteResourceCommand(clientOpts *argocdclient.ClientOptions)
}
func parentChildInfo(nodes []v1alpha1.ResourceNode) (map[string]v1alpha1.ResourceNode, map[string][]string, map[string]struct{}) {
- mapUIDToNode := make(map[string]v1alpha1.ResourceNode)
+ mapUidToNode := make(map[string]v1alpha1.ResourceNode)
mapParentToChild := make(map[string][]string)
parentNode := make(map[string]struct{})
for _, node := range nodes {
- mapUIDToNode[node.UID] = node
+ mapUidToNode[node.UID] = node
if len(node.ParentRefs) > 0 {
_, ok := mapParentToChild[node.ParentRefs[0].UID]
@@ -182,7 +182,7 @@ func parentChildInfo(nodes []v1alpha1.ResourceNode) (map[string]v1alpha1.Resourc
parentNode[node.UID] = struct{}{}
}
}
- return mapUIDToNode, mapParentToChild, parentNode
+ return mapUidToNode, mapParentToChild, parentNode
}
func printDetailedTreeViewAppResourcesNotOrphaned(nodeMapping map[string]v1alpha1.ResourceNode, parentChildMapping map[string][]string, parentNodes map[string]struct{}, w *tabwriter.Writer) {
@@ -211,33 +211,32 @@ func printTreeViewAppResourcesOrphaned(nodeMapping map[string]v1alpha1.ResourceN
func printResources(listAll bool, orphaned bool, appResourceTree *v1alpha1.ApplicationTree, output string) {
w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
- switch output {
- case "tree=detailed":
+ if output == "tree=detailed" {
fmt.Fprintf(w, "GROUP\tKIND\tNAMESPACE\tNAME\tORPHANED\tAGE\tHEALTH\tREASON\n")
if !orphaned || listAll {
- mapUIDToNode, mapParentToChild, parentNode := parentChildInfo(appResourceTree.Nodes)
- printDetailedTreeViewAppResourcesNotOrphaned(mapUIDToNode, mapParentToChild, parentNode, w)
+ mapUidToNode, mapParentToChild, parentNode := parentChildInfo(appResourceTree.Nodes)
+ printDetailedTreeViewAppResourcesNotOrphaned(mapUidToNode, mapParentToChild, parentNode, w)
}
if orphaned || listAll {
- mapUIDToNode, mapParentToChild, parentNode := parentChildInfo(appResourceTree.OrphanedNodes)
- printDetailedTreeViewAppResourcesOrphaned(mapUIDToNode, mapParentToChild, parentNode, w)
+ mapUidToNode, mapParentToChild, parentNode := parentChildInfo(appResourceTree.OrphanedNodes)
+ printDetailedTreeViewAppResourcesOrphaned(mapUidToNode, mapParentToChild, parentNode, w)
}
- case "tree":
+ } else if output == "tree" {
fmt.Fprintf(w, "GROUP\tKIND\tNAMESPACE\tNAME\tORPHANED\n")
if !orphaned || listAll {
- mapUIDToNode, mapParentToChild, parentNode := parentChildInfo(appResourceTree.Nodes)
- printTreeViewAppResourcesNotOrphaned(mapUIDToNode, mapParentToChild, parentNode, w)
+ mapUidToNode, mapParentToChild, parentNode := parentChildInfo(appResourceTree.Nodes)
+ printTreeViewAppResourcesNotOrphaned(mapUidToNode, mapParentToChild, parentNode, w)
}
if orphaned || listAll {
- mapUIDToNode, mapParentToChild, parentNode := parentChildInfo(appResourceTree.OrphanedNodes)
- printTreeViewAppResourcesOrphaned(mapUIDToNode, mapParentToChild, parentNode, w)
+ mapUidToNode, mapParentToChild, parentNode := parentChildInfo(appResourceTree.OrphanedNodes)
+ printTreeViewAppResourcesOrphaned(mapUidToNode, mapParentToChild, parentNode, w)
}
- default:
- headers := []any{"GROUP", "KIND", "NAMESPACE", "NAME", "ORPHANED"}
+ } else {
+ headers := []interface{}{"GROUP", "KIND", "NAMESPACE", "NAME", "ORPHANED"}
fmtStr := "%s\t%s\t%s\t%s\t%s\n"
_, _ = fmt.Fprintf(w, fmtStr, headers...)
if !orphaned || listAll {
@@ -272,7 +271,7 @@ func NewApplicationListResourcesCommand(clientOpts *argocdclient.ClientOptions)
listAll := !c.Flag("orphaned").Changed
appName, appNs := argo.ParseFromQualifiedName(args[0], "")
conn, appIf := headless.NewClientOrDie(clientOpts, c).NewApplicationClientOrDie()
- defer utilio.Close(conn)
+ defer argoio.Close(conn)
appResourceTree, err := appIf.ResourceTree(ctx, &applicationpkg.ResourcesQuery{
ApplicationName: &appName,
AppNamespace: &appNs,
diff --git a/cmd/argocd/commands/app_test.go b/cmd/argocd/commands/app_test.go
index 3e8b3182b9..57aede02a5 100644
--- a/cmd/argocd/commands/app_test.go
+++ b/cmd/argocd/commands/app_test.go
@@ -12,6 +12,32 @@ import (
"testing"
"time"
+ "google.golang.org/grpc"
+ "k8s.io/apimachinery/pkg/watch"
+
+ "github.com/argoproj/argo-cd/v2/reposerver/apiclient"
+
+ v1 "k8s.io/api/core/v1"
+
+ "sigs.k8s.io/yaml"
+
+ argocdclient "github.com/argoproj/argo-cd/v2/pkg/apiclient"
+ accountpkg "github.com/argoproj/argo-cd/v2/pkg/apiclient/account"
+ applicationpkg "github.com/argoproj/argo-cd/v2/pkg/apiclient/application"
+ applicationsetpkg "github.com/argoproj/argo-cd/v2/pkg/apiclient/applicationset"
+ certificatepkg "github.com/argoproj/argo-cd/v2/pkg/apiclient/certificate"
+ clusterpkg "github.com/argoproj/argo-cd/v2/pkg/apiclient/cluster"
+ gpgkeypkg "github.com/argoproj/argo-cd/v2/pkg/apiclient/gpgkey"
+ notificationpkg "github.com/argoproj/argo-cd/v2/pkg/apiclient/notification"
+ projectpkg "github.com/argoproj/argo-cd/v2/pkg/apiclient/project"
+ repocredspkg "github.com/argoproj/argo-cd/v2/pkg/apiclient/repocreds"
+ repositorypkg "github.com/argoproj/argo-cd/v2/pkg/apiclient/repository"
+ sessionpkg "github.com/argoproj/argo-cd/v2/pkg/apiclient/session"
+ settingspkg "github.com/argoproj/argo-cd/v2/pkg/apiclient/settings"
+ 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"
@@ -20,32 +46,11 @@ import (
"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"
- "sigs.k8s.io/yaml"
-
- argocdclient "github.com/argoproj/argo-cd/v3/pkg/apiclient"
- accountpkg "github.com/argoproj/argo-cd/v3/pkg/apiclient/account"
- applicationpkg "github.com/argoproj/argo-cd/v3/pkg/apiclient/application"
- applicationsetpkg "github.com/argoproj/argo-cd/v3/pkg/apiclient/applicationset"
- certificatepkg "github.com/argoproj/argo-cd/v3/pkg/apiclient/certificate"
- clusterpkg "github.com/argoproj/argo-cd/v3/pkg/apiclient/cluster"
- gpgkeypkg "github.com/argoproj/argo-cd/v3/pkg/apiclient/gpgkey"
- notificationpkg "github.com/argoproj/argo-cd/v3/pkg/apiclient/notification"
- projectpkg "github.com/argoproj/argo-cd/v3/pkg/apiclient/project"
- repocredspkg "github.com/argoproj/argo-cd/v3/pkg/apiclient/repocreds"
- repositorypkg "github.com/argoproj/argo-cd/v3/pkg/apiclient/repository"
- sessionpkg "github.com/argoproj/argo-cd/v3/pkg/apiclient/session"
- settingspkg "github.com/argoproj/argo-cd/v3/pkg/apiclient/settings"
- versionpkg "github.com/argoproj/argo-cd/v3/pkg/apiclient/version"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- "github.com/argoproj/argo-cd/v3/reposerver/apiclient"
+ k8swatch "k8s.io/apimachinery/pkg/watch"
)
func Test_getInfos(t *testing.T) {
@@ -116,7 +121,7 @@ func TestFindRevisionHistoryWithoutPassedId(t *testing.T) {
status := v1alpha1.ApplicationStatus{
Resources: nil,
Sync: v1alpha1.SyncStatus{},
- Health: v1alpha1.AppHealthStatus{},
+ Health: v1alpha1.HealthStatus{},
History: histories,
Conditions: nil,
ReconciledAt: nil,
@@ -224,7 +229,7 @@ func TestFindRevisionHistoryWithoutPassedIdWithMultipleSources(t *testing.T) {
status := v1alpha1.ApplicationStatus{
Resources: nil,
Sync: v1alpha1.SyncStatus{},
- Health: v1alpha1.AppHealthStatus{},
+ Health: v1alpha1.HealthStatus{},
History: histories,
Conditions: nil,
ReconciledAt: nil,
@@ -277,7 +282,7 @@ func TestFindRevisionHistoryWithoutPassedIdAndEmptyHistoryList(t *testing.T) {
status := v1alpha1.ApplicationStatus{
Resources: nil,
Sync: v1alpha1.SyncStatus{},
- Health: v1alpha1.AppHealthStatus{},
+ Health: v1alpha1.HealthStatus{},
History: histories,
Conditions: nil,
ReconciledAt: nil,
@@ -295,7 +300,7 @@ func TestFindRevisionHistoryWithoutPassedIdAndEmptyHistoryList(t *testing.T) {
require.Error(t, err, "Find revision history should fail with errors")
require.Nil(t, history, "History should be empty")
- require.EqualError(t, err, "application '' should have at least two successful deployments", "Find revision history should fail with correct error message")
+ require.EqualError(t, err, "Application '' should have at least two successful deployments", "Find revision history should fail with correct error message")
}
func TestFindRevisionHistoryWithPassedId(t *testing.T) {
@@ -308,7 +313,7 @@ func TestFindRevisionHistoryWithPassedId(t *testing.T) {
status := v1alpha1.ApplicationStatus{
Resources: nil,
Sync: v1alpha1.SyncStatus{},
- Health: v1alpha1.AppHealthStatus{},
+ Health: v1alpha1.HealthStatus{},
History: histories,
Conditions: nil,
ReconciledAt: nil,
@@ -338,7 +343,7 @@ func TestFindRevisionHistoryWithPassedIdThatNotExist(t *testing.T) {
status := v1alpha1.ApplicationStatus{
Resources: nil,
Sync: v1alpha1.SyncStatus{},
- Health: v1alpha1.AppHealthStatus{},
+ Health: v1alpha1.HealthStatus{},
History: histories,
Conditions: nil,
ReconciledAt: nil,
@@ -356,26 +361,26 @@ func TestFindRevisionHistoryWithPassedIdThatNotExist(t *testing.T) {
require.Error(t, err, "Find revision history should fail with errors")
require.Nil(t, history, "History should be not found")
- require.EqualError(t, err, "application '' does not have deployment id '4' in history", "Find revision history should fail with correct error message")
+ require.EqualError(t, err, "Application '' does not have deployment id '4' in history\n", "Find revision history should fail with correct error message")
}
func Test_groupObjsByKey(t *testing.T) {
localObjs := []*unstructured.Unstructured{
{
- Object: map[string]any{
+ Object: map[string]interface{}{
"apiVersion": "v1",
"kind": "Pod",
- "metadata": map[string]any{
+ "metadata": map[string]interface{}{
"name": "pod-name",
"namespace": "default",
},
},
},
{
- Object: map[string]any{
+ Object: map[string]interface{}{
"apiVersion": "apiextensions.k8s.io/v1",
"kind": "CustomResourceDefinition",
- "metadata": map[string]any{
+ "metadata": map[string]interface{}{
"name": "certificates.cert-manager.io",
},
},
@@ -383,20 +388,20 @@ func Test_groupObjsByKey(t *testing.T) {
}
liveObjs := []*unstructured.Unstructured{
{
- Object: map[string]any{
+ Object: map[string]interface{}{
"apiVersion": "v1",
"kind": "Pod",
- "metadata": map[string]any{
+ "metadata": map[string]interface{}{
"name": "pod-name",
"namespace": "default",
},
},
},
{
- Object: map[string]any{
+ Object: map[string]interface{}{
"apiVersion": "apiextensions.k8s.io/v1",
"kind": "CustomResourceDefinition",
- "metadata": map[string]any{
+ "metadata": map[string]interface{}{
"name": "certificates.cert-manager.io",
},
},
@@ -692,8 +697,9 @@ func TestPrintAppSummaryTable(t *testing.T) {
Sync: v1alpha1.SyncStatus{
Status: v1alpha1.SyncStatusCodeOutOfSync,
},
- Health: v1alpha1.AppHealthStatus{
- Status: health.HealthStatusProgressing,
+ Health: v1alpha1.HealthStatus{
+ Status: health.HealthStatusProgressing,
+ Message: "health-message",
},
},
}
@@ -746,7 +752,7 @@ SyncWindow: Sync Denied
Assigned Windows: allow:0 0 * * *:24h,deny:0 0 * * *:24h,allow:0 0 * * *:24h
Sync Policy: Automated (Prune)
Sync Status: OutOfSync from master
-Health Status: Progressing
+Health Status: Progressing (health-message)
`
assert.Equalf(t, expectation, output, "Incorrect print app summary output %q, should be %q", output, expectation)
}
@@ -786,8 +792,9 @@ func TestPrintAppSummaryTable_MultipleSources(t *testing.T) {
Sync: v1alpha1.SyncStatus{
Status: v1alpha1.SyncStatusCodeOutOfSync,
},
- Health: v1alpha1.AppHealthStatus{
- Status: health.HealthStatusProgressing,
+ Health: v1alpha1.HealthStatus{
+ Status: health.HealthStatusProgressing,
+ Message: "health-message",
},
},
}
@@ -843,7 +850,7 @@ SyncWindow: Sync Denied
Assigned Windows: allow:0 0 * * *:24h,deny:0 0 * * *:24h,allow:0 0 * * *:24h
Sync Policy: Automated (Prune)
Sync Status: OutOfSync from master
-Health Status: Progressing
+Health Status: Progressing (health-message)
`
assert.Equalf(t, expectation, output, "Incorrect print app summary output %q, should be %q", output, expectation)
}
@@ -1028,9 +1035,10 @@ func TestTargetObjects_invalid(t *testing.T) {
}
func TestCheckForDeleteEvent(t *testing.T) {
+ ctx := context.Background()
fakeClient := new(fakeAcdClient)
- checkForDeleteEvent(t.Context(), fakeClient, "testApp")
+ checkForDeleteEvent(ctx, fakeClient, "testApp")
}
func TestPrintApplicationNames(t *testing.T) {
@@ -1050,10 +1058,9 @@ func TestPrintApplicationNames(t *testing.T) {
func Test_unset(t *testing.T) {
kustomizeSource := &v1alpha1.ApplicationSource{
Kustomize: &v1alpha1.ApplicationSourceKustomize{
- IgnoreMissingComponents: true,
- NamePrefix: "some-prefix",
- NameSuffix: "some-suffix",
- Version: "123",
+ NamePrefix: "some-prefix",
+ NameSuffix: "some-suffix",
+ Version: "123",
Images: v1alpha1.KustomizeImages{
"old1=new:tag",
"old2=new:tag",
@@ -1110,7 +1117,7 @@ func Test_unset(t *testing.T) {
assert.Equal(t, "some-prefix", kustomizeSource.Kustomize.NamePrefix)
updated, nothingToUnset := unset(kustomizeSource, unsetOpts{namePrefix: true})
- assert.Empty(t, kustomizeSource.Kustomize.NamePrefix)
+ assert.Equal(t, "", kustomizeSource.Kustomize.NamePrefix)
assert.True(t, updated)
assert.False(t, nothingToUnset)
updated, nothingToUnset = unset(kustomizeSource, unsetOpts{namePrefix: true})
@@ -1119,7 +1126,7 @@ func Test_unset(t *testing.T) {
assert.Equal(t, "some-suffix", kustomizeSource.Kustomize.NameSuffix)
updated, nothingToUnset = unset(kustomizeSource, unsetOpts{nameSuffix: true})
- assert.Empty(t, kustomizeSource.Kustomize.NameSuffix)
+ assert.Equal(t, "", kustomizeSource.Kustomize.NameSuffix)
assert.True(t, updated)
assert.False(t, nothingToUnset)
updated, nothingToUnset = unset(kustomizeSource, unsetOpts{nameSuffix: true})
@@ -1128,7 +1135,7 @@ func Test_unset(t *testing.T) {
assert.Equal(t, "123", kustomizeSource.Kustomize.Version)
updated, nothingToUnset = unset(kustomizeSource, unsetOpts{kustomizeVersion: true})
- assert.Empty(t, kustomizeSource.Kustomize.Version)
+ assert.Equal(t, "", kustomizeSource.Kustomize.Version)
assert.True(t, updated)
assert.False(t, nothingToUnset)
updated, nothingToUnset = unset(kustomizeSource, unsetOpts{kustomizeVersion: true})
@@ -1153,15 +1160,6 @@ func Test_unset(t *testing.T) {
assert.False(t, updated)
assert.False(t, nothingToUnset)
- assert.True(t, kustomizeSource.Kustomize.IgnoreMissingComponents)
- updated, nothingToUnset = unset(kustomizeSource, unsetOpts{ignoreMissingComponents: true})
- assert.False(t, kustomizeSource.Kustomize.IgnoreMissingComponents)
- assert.True(t, updated)
- assert.False(t, nothingToUnset)
- updated, nothingToUnset = unset(kustomizeSource, unsetOpts{ignoreMissingComponents: true})
- assert.False(t, updated)
- assert.False(t, nothingToUnset)
-
assert.Len(t, helmSource.Helm.Parameters, 2)
updated, nothingToUnset = unset(helmSource, unsetOpts{parameters: []string{"name-1"}})
assert.Len(t, helmSource.Helm.Parameters, 1)
@@ -1182,7 +1180,7 @@ func Test_unset(t *testing.T) {
assert.Equal(t, "some: yaml", helmSource.Helm.ValuesString())
updated, nothingToUnset = unset(helmSource, unsetOpts{valuesLiteral: true})
- assert.Empty(t, helmSource.Helm.ValuesString())
+ assert.Equal(t, "", helmSource.Helm.ValuesString())
assert.True(t, updated)
assert.False(t, nothingToUnset)
updated, nothingToUnset = unset(helmSource, unsetOpts{valuesLiteral: true})
@@ -1560,7 +1558,7 @@ func TestPrintApplicationTableNotWide(t *testing.T) {
Sync: v1alpha1.SyncStatus{
Status: "OutOfSync",
},
- Health: v1alpha1.AppHealthStatus{
+ Health: v1alpha1.HealthStatus{
Status: "Healthy",
},
},
@@ -1596,7 +1594,7 @@ func TestPrintApplicationTableWide(t *testing.T) {
Sync: v1alpha1.SyncStatus{
Status: "OutOfSync",
},
- Health: v1alpha1.AppHealthStatus{
+ Health: v1alpha1.HealthStatus{
Status: "Healthy",
},
},
@@ -1869,7 +1867,7 @@ func testApp(name, project string, labels map[string]string, annotations map[str
func TestWaitOnApplicationStatus_JSON_YAML_WideOutput(t *testing.T) {
acdClient := &customAcdClient{&fakeAcdClient{}}
- ctx := t.Context()
+ ctx := context.Background()
var selectResource []*v1alpha1.SyncOperationResource
watch := watchOpts{
sync: false,
@@ -1920,72 +1918,7 @@ Source:
SyncWindow: Sync Allowed
Sync Policy: Automated (Prune)
Sync Status: OutOfSync from master
-Health Status: Progressing
-
-Operation: Sync
-Sync Revision: revision
-Phase:
-Start: 0001-01-01 00:00:00 +0000 UTC
-Finished: 2020-11-10 23:00:00 +0000 UTC
-Duration: 2333448h16m18.871345152s
-Message: test
-
-GROUP KIND NAMESPACE NAME STATUS HEALTH HOOK MESSAGE
- Service default service-name1 Synced Healthy
-apps Deployment default test Synced Healthy
-`
- expectation = fmt.Sprintf(expectation, timeStr, timeStr)
- expectationParts := strings.Split(expectation, "\n")
- slices.Sort(expectationParts)
- expectationSorted := strings.Join(expectationParts, "\n")
- outputParts := strings.Split(output, "\n")
- slices.Sort(outputParts)
- outputSorted := strings.Join(outputParts, "\n")
- // Need to compare sorted since map entries may not keep a specific order during serialization, leading to flakiness.
- assert.Equalf(t, expectationSorted, outputSorted, "Incorrect output %q, should be %q (items order doesn't matter)", output, expectation)
-}
-
-func TestWaitOnApplicationStatus_JSON_YAML_WideOutput_With_Timeout(t *testing.T) {
- acdClient := &customAcdClient{&fakeAcdClient{simulateTimeout: 15}}
- ctx := t.Context()
- var selectResource []*v1alpha1.SyncOperationResource
- watch := watchOpts{
- sync: false,
- health: false,
- operation: true,
- suspended: false,
- }
- watch = getWatchOpts(watch)
-
- output, _ := captureOutput(func() error {
- _, _, _ = waitOnApplicationStatus(ctx, acdClient, "app-name", 5, watch, selectResource, "")
- return nil
- })
- timeStr := time.Now().Format("2006-01-02T15:04:05-07:00")
-
- expectation := `TIMESTAMP GROUP KIND NAMESPACE NAME STATUS HEALTH HOOK MESSAGE
-%s Service default service-name1 Synced Healthy
-%s apps Deployment default test Synced Healthy
-
-The command timed out waiting for the conditions to be met.
-
-This is the state of the app after wait timed out:
-
-Name: argocd/test
-Project: default
-Server: local
-Namespace: argocd
-URL: http://localhost:8080/applications/app-name
-Source:
-- Repo: test
- Target: master
- Path: /test
- Helm Values: path1,path2
- Name Prefix: prefix
-SyncWindow: Sync Allowed
-Sync Policy: Automated (Prune)
-Sync Status: OutOfSync from master
-Health Status: Progressing
+Health Status: Progressing (health-message)
Operation: Sync
Sync Revision: revision
@@ -2014,7 +1947,7 @@ type customAcdClient struct {
*fakeAcdClient
}
-func (c *customAcdClient) WatchApplicationWithRetry(ctx context.Context, _ string, _ string) chan *v1alpha1.ApplicationWatchEvent {
+func (c *customAcdClient) WatchApplicationWithRetry(ctx context.Context, appName string, revision string) chan *v1alpha1.ApplicationWatchEvent {
appEventsCh := make(chan *v1alpha1.ApplicationWatchEvent)
_, appClient := c.NewApplicationClientOrDie()
app, _ := appClient.Get(ctx, &applicationpkg.ApplicationQuery{})
@@ -2028,7 +1961,6 @@ func (c *customAcdClient) WatchApplicationWithRetry(ctx context.Context, _ strin
}
go func() {
- time.Sleep(time.Duration(c.simulateTimeout) * time.Second)
appEventsCh <- &v1alpha1.ApplicationWatchEvent{
Type: watch.Bookmark,
Application: newApp,
@@ -2055,19 +1987,19 @@ func (c *fakeConnection) Close() error {
type fakeSettingsServiceClient struct{}
-func (f fakeSettingsServiceClient) Get(_ context.Context, _ *settingspkg.SettingsQuery, _ ...grpc.CallOption) (*settingspkg.Settings, error) {
+func (f fakeSettingsServiceClient) Get(ctx context.Context, in *settingspkg.SettingsQuery, opts ...grpc.CallOption) (*settingspkg.Settings, error) {
return &settingspkg.Settings{
URL: "http://localhost:8080",
}, nil
}
-func (f fakeSettingsServiceClient) GetPlugins(_ context.Context, _ *settingspkg.SettingsQuery, _ ...grpc.CallOption) (*settingspkg.SettingsPluginsResponse, error) {
+func (f fakeSettingsServiceClient) GetPlugins(ctx context.Context, in *settingspkg.SettingsQuery, opts ...grpc.CallOption) (*settingspkg.SettingsPluginsResponse, error) {
return nil, nil
}
type fakeAppServiceClient struct{}
-func (c *fakeAppServiceClient) Get(_ context.Context, _ *applicationpkg.ApplicationQuery, _ ...grpc.CallOption) (*v1alpha1.Application, error) {
+func (c *fakeAppServiceClient) Get(ctx context.Context, in *applicationpkg.ApplicationQuery, opts ...grpc.CallOption) (*v1alpha1.Application, error) {
time := metav1.Date(2020, time.November, 10, 23, 0, 0, 0, time.UTC)
return &v1alpha1.Application{
ObjectMeta: metav1.ObjectMeta{
@@ -2127,124 +2059,123 @@ func (c *fakeAppServiceClient) Get(_ context.Context, _ *applicationpkg.Applicat
Sync: v1alpha1.SyncStatus{
Status: v1alpha1.SyncStatusCodeOutOfSync,
},
- Health: v1alpha1.AppHealthStatus{
- Status: health.HealthStatusProgressing,
+ Health: v1alpha1.HealthStatus{
+ Status: health.HealthStatusProgressing,
+ Message: "health-message",
},
},
}, nil
}
-func (c *fakeAppServiceClient) List(_ context.Context, _ *applicationpkg.ApplicationQuery, _ ...grpc.CallOption) (*v1alpha1.ApplicationList, error) {
+func (c *fakeAppServiceClient) List(ctx context.Context, in *applicationpkg.ApplicationQuery, opts ...grpc.CallOption) (*v1alpha1.ApplicationList, error) {
return nil, nil
}
-func (c *fakeAppServiceClient) ListResourceEvents(_ context.Context, _ *applicationpkg.ApplicationResourceEventsQuery, _ ...grpc.CallOption) (*corev1.EventList, error) {
+func (c *fakeAppServiceClient) ListResourceEvents(ctx context.Context, in *applicationpkg.ApplicationResourceEventsQuery, opts ...grpc.CallOption) (*v1.EventList, error) {
return nil, nil
}
-func (c *fakeAppServiceClient) Watch(_ context.Context, _ *applicationpkg.ApplicationQuery, _ ...grpc.CallOption) (applicationpkg.ApplicationService_WatchClient, error) {
+func (c *fakeAppServiceClient) Watch(ctx context.Context, in *applicationpkg.ApplicationQuery, opts ...grpc.CallOption) (applicationpkg.ApplicationService_WatchClient, error) {
return nil, nil
}
-func (c *fakeAppServiceClient) Create(_ context.Context, _ *applicationpkg.ApplicationCreateRequest, _ ...grpc.CallOption) (*v1alpha1.Application, error) {
+func (c *fakeAppServiceClient) Create(ctx context.Context, in *applicationpkg.ApplicationCreateRequest, opts ...grpc.CallOption) (*v1alpha1.Application, error) {
return nil, nil
}
-func (c *fakeAppServiceClient) GetApplicationSyncWindows(_ context.Context, _ *applicationpkg.ApplicationSyncWindowsQuery, _ ...grpc.CallOption) (*applicationpkg.ApplicationSyncWindowsResponse, error) {
+func (c *fakeAppServiceClient) GetApplicationSyncWindows(ctx context.Context, in *applicationpkg.ApplicationSyncWindowsQuery, opts ...grpc.CallOption) (*applicationpkg.ApplicationSyncWindowsResponse, error) {
return nil, nil
}
-func (c *fakeAppServiceClient) RevisionMetadata(_ context.Context, _ *applicationpkg.RevisionMetadataQuery, _ ...grpc.CallOption) (*v1alpha1.RevisionMetadata, error) {
+func (c *fakeAppServiceClient) RevisionMetadata(ctx context.Context, in *applicationpkg.RevisionMetadataQuery, opts ...grpc.CallOption) (*v1alpha1.RevisionMetadata, error) {
return nil, nil
}
-func (c *fakeAppServiceClient) RevisionChartDetails(_ context.Context, _ *applicationpkg.RevisionMetadataQuery, _ ...grpc.CallOption) (*v1alpha1.ChartDetails, error) {
+func (c *fakeAppServiceClient) RevisionChartDetails(ctx context.Context, in *applicationpkg.RevisionMetadataQuery, opts ...grpc.CallOption) (*v1alpha1.ChartDetails, error) {
return nil, nil
}
-func (c *fakeAppServiceClient) GetManifests(_ context.Context, _ *applicationpkg.ApplicationManifestQuery, _ ...grpc.CallOption) (*apiclient.ManifestResponse, error) {
+func (c *fakeAppServiceClient) GetManifests(ctx context.Context, in *applicationpkg.ApplicationManifestQuery, opts ...grpc.CallOption) (*apiclient.ManifestResponse, error) {
return nil, nil
}
-func (c *fakeAppServiceClient) GetManifestsWithFiles(_ context.Context, _ ...grpc.CallOption) (applicationpkg.ApplicationService_GetManifestsWithFilesClient, error) {
+func (c *fakeAppServiceClient) GetManifestsWithFiles(ctx context.Context, opts ...grpc.CallOption) (applicationpkg.ApplicationService_GetManifestsWithFilesClient, error) {
return nil, nil
}
-func (c *fakeAppServiceClient) Update(_ context.Context, _ *applicationpkg.ApplicationUpdateRequest, _ ...grpc.CallOption) (*v1alpha1.Application, error) {
+func (c *fakeAppServiceClient) Update(ctx context.Context, in *applicationpkg.ApplicationUpdateRequest, opts ...grpc.CallOption) (*v1alpha1.Application, error) {
return nil, nil
}
-func (c *fakeAppServiceClient) UpdateSpec(_ context.Context, _ *applicationpkg.ApplicationUpdateSpecRequest, _ ...grpc.CallOption) (*v1alpha1.ApplicationSpec, error) {
+func (c *fakeAppServiceClient) UpdateSpec(ctx context.Context, in *applicationpkg.ApplicationUpdateSpecRequest, opts ...grpc.CallOption) (*v1alpha1.ApplicationSpec, error) {
return nil, nil
}
-func (c *fakeAppServiceClient) Patch(_ context.Context, _ *applicationpkg.ApplicationPatchRequest, _ ...grpc.CallOption) (*v1alpha1.Application, error) {
+func (c *fakeAppServiceClient) Patch(ctx context.Context, in *applicationpkg.ApplicationPatchRequest, opts ...grpc.CallOption) (*v1alpha1.Application, error) {
return nil, nil
}
-func (c *fakeAppServiceClient) Delete(_ context.Context, _ *applicationpkg.ApplicationDeleteRequest, _ ...grpc.CallOption) (*applicationpkg.ApplicationResponse, error) {
+func (c *fakeAppServiceClient) Delete(ctx context.Context, in *applicationpkg.ApplicationDeleteRequest, opts ...grpc.CallOption) (*applicationpkg.ApplicationResponse, error) {
return nil, nil
}
-func (c *fakeAppServiceClient) Sync(_ context.Context, _ *applicationpkg.ApplicationSyncRequest, _ ...grpc.CallOption) (*v1alpha1.Application, error) {
+func (c *fakeAppServiceClient) Sync(ctx context.Context, in *applicationpkg.ApplicationSyncRequest, opts ...grpc.CallOption) (*v1alpha1.Application, error) {
return nil, nil
}
-func (c *fakeAppServiceClient) ManagedResources(_ context.Context, _ *applicationpkg.ResourcesQuery, _ ...grpc.CallOption) (*applicationpkg.ManagedResourcesResponse, error) {
+func (c *fakeAppServiceClient) ManagedResources(ctx context.Context, in *applicationpkg.ResourcesQuery, opts ...grpc.CallOption) (*applicationpkg.ManagedResourcesResponse, error) {
return nil, nil
}
-func (c *fakeAppServiceClient) ResourceTree(_ context.Context, _ *applicationpkg.ResourcesQuery, _ ...grpc.CallOption) (*v1alpha1.ApplicationTree, error) {
+func (c *fakeAppServiceClient) ResourceTree(ctx context.Context, in *applicationpkg.ResourcesQuery, opts ...grpc.CallOption) (*v1alpha1.ApplicationTree, error) {
return nil, nil
}
-func (c *fakeAppServiceClient) WatchResourceTree(_ context.Context, _ *applicationpkg.ResourcesQuery, _ ...grpc.CallOption) (applicationpkg.ApplicationService_WatchResourceTreeClient, error) {
+func (c *fakeAppServiceClient) WatchResourceTree(ctx context.Context, in *applicationpkg.ResourcesQuery, opts ...grpc.CallOption) (applicationpkg.ApplicationService_WatchResourceTreeClient, error) {
return nil, nil
}
-func (c *fakeAppServiceClient) Rollback(_ context.Context, _ *applicationpkg.ApplicationRollbackRequest, _ ...grpc.CallOption) (*v1alpha1.Application, error) {
+func (c *fakeAppServiceClient) Rollback(ctx context.Context, in *applicationpkg.ApplicationRollbackRequest, opts ...grpc.CallOption) (*v1alpha1.Application, error) {
return nil, nil
}
-func (c *fakeAppServiceClient) TerminateOperation(_ context.Context, _ *applicationpkg.OperationTerminateRequest, _ ...grpc.CallOption) (*applicationpkg.OperationTerminateResponse, error) {
+func (c *fakeAppServiceClient) TerminateOperation(ctx context.Context, in *applicationpkg.OperationTerminateRequest, opts ...grpc.CallOption) (*applicationpkg.OperationTerminateResponse, error) {
return nil, nil
}
-func (c *fakeAppServiceClient) GetResource(_ context.Context, _ *applicationpkg.ApplicationResourceRequest, _ ...grpc.CallOption) (*applicationpkg.ApplicationResourceResponse, error) {
+func (c *fakeAppServiceClient) GetResource(ctx context.Context, in *applicationpkg.ApplicationResourceRequest, opts ...grpc.CallOption) (*applicationpkg.ApplicationResourceResponse, error) {
return nil, nil
}
-func (c *fakeAppServiceClient) PatchResource(_ context.Context, _ *applicationpkg.ApplicationResourcePatchRequest, _ ...grpc.CallOption) (*applicationpkg.ApplicationResourceResponse, error) {
+func (c *fakeAppServiceClient) PatchResource(ctx context.Context, in *applicationpkg.ApplicationResourcePatchRequest, opts ...grpc.CallOption) (*applicationpkg.ApplicationResourceResponse, error) {
return nil, nil
}
-func (c *fakeAppServiceClient) ListResourceActions(_ context.Context, _ *applicationpkg.ApplicationResourceRequest, _ ...grpc.CallOption) (*applicationpkg.ResourceActionsListResponse, error) {
+func (c *fakeAppServiceClient) ListResourceActions(ctx context.Context, in *applicationpkg.ApplicationResourceRequest, opts ...grpc.CallOption) (*applicationpkg.ResourceActionsListResponse, error) {
return nil, nil
}
-func (c *fakeAppServiceClient) RunResourceAction(_ context.Context, _ *applicationpkg.ResourceActionRunRequest, _ ...grpc.CallOption) (*applicationpkg.ApplicationResponse, error) {
+func (c *fakeAppServiceClient) RunResourceAction(ctx context.Context, in *applicationpkg.ResourceActionRunRequest, opts ...grpc.CallOption) (*applicationpkg.ApplicationResponse, error) {
return nil, nil
}
-func (c *fakeAppServiceClient) DeleteResource(_ context.Context, _ *applicationpkg.ApplicationResourceDeleteRequest, _ ...grpc.CallOption) (*applicationpkg.ApplicationResponse, error) {
+func (c *fakeAppServiceClient) DeleteResource(ctx context.Context, in *applicationpkg.ApplicationResourceDeleteRequest, opts ...grpc.CallOption) (*applicationpkg.ApplicationResponse, error) {
return nil, nil
}
-func (c *fakeAppServiceClient) PodLogs(_ context.Context, _ *applicationpkg.ApplicationPodLogsQuery, _ ...grpc.CallOption) (applicationpkg.ApplicationService_PodLogsClient, error) {
+func (c *fakeAppServiceClient) PodLogs(ctx context.Context, in *applicationpkg.ApplicationPodLogsQuery, opts ...grpc.CallOption) (applicationpkg.ApplicationService_PodLogsClient, error) {
return nil, nil
}
-func (c *fakeAppServiceClient) ListLinks(_ context.Context, _ *applicationpkg.ListAppLinksRequest, _ ...grpc.CallOption) (*applicationpkg.LinksResponse, error) {
+func (c *fakeAppServiceClient) ListLinks(ctx context.Context, in *applicationpkg.ListAppLinksRequest, opts ...grpc.CallOption) (*applicationpkg.LinksResponse, error) {
return nil, nil
}
-func (c *fakeAppServiceClient) ListResourceLinks(_ context.Context, _ *applicationpkg.ApplicationResourceRequest, _ ...grpc.CallOption) (*applicationpkg.LinksResponse, error) {
+func (c *fakeAppServiceClient) ListResourceLinks(ctx context.Context, in *applicationpkg.ApplicationResourceRequest, opts ...grpc.CallOption) (*applicationpkg.LinksResponse, error) {
return nil, nil
}
-type fakeAcdClient struct {
- simulateTimeout uint
-}
+type fakeAcdClient struct{}
func (c *fakeAcdClient) ClientOptions() argocdclient.ClientOptions {
return argocdclient.ClientOptions{}
@@ -2358,15 +2289,15 @@ func (c *fakeAcdClient) NewAccountClientOrDie() (io.Closer, accountpkg.AccountSe
return nil, nil
}
-func (c *fakeAcdClient) WatchApplicationWithRetry(_ context.Context, _ string, _ string) chan *v1alpha1.ApplicationWatchEvent {
+func (c *fakeAcdClient) WatchApplicationWithRetry(ctx context.Context, appName string, revision string) chan *v1alpha1.ApplicationWatchEvent {
appEventsCh := make(chan *v1alpha1.ApplicationWatchEvent)
go func() {
modifiedEvent := new(v1alpha1.ApplicationWatchEvent)
- modifiedEvent.Type = watch.Modified
+ modifiedEvent.Type = k8swatch.Modified
appEventsCh <- modifiedEvent
deletedEvent := new(v1alpha1.ApplicationWatchEvent)
- deletedEvent.Type = watch.Deleted
+ deletedEvent.Type = k8swatch.Deleted
appEventsCh <- deletedEvent
}()
return appEventsCh
diff --git a/cmd/argocd/commands/applicationset.go b/cmd/argocd/commands/applicationset.go
index 97ce8c5d8e..3dcc905182 100644
--- a/cmd/argocd/commands/applicationset.go
+++ b/cmd/argocd/commands/applicationset.go
@@ -11,18 +11,18 @@ import (
"github.com/spf13/cobra"
"google.golang.org/grpc/codes"
- "github.com/argoproj/argo-cd/v3/cmd/argocd/commands/admin"
- "github.com/argoproj/argo-cd/v3/cmd/argocd/commands/headless"
- "github.com/argoproj/argo-cd/v3/cmd/argocd/commands/utils"
- cmdutil "github.com/argoproj/argo-cd/v3/cmd/util"
- argocdclient "github.com/argoproj/argo-cd/v3/pkg/apiclient"
- "github.com/argoproj/argo-cd/v3/pkg/apiclient/applicationset"
- arogappsetv1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- "github.com/argoproj/argo-cd/v3/util/argo"
- "github.com/argoproj/argo-cd/v3/util/errors"
- "github.com/argoproj/argo-cd/v3/util/grpc"
- utilio "github.com/argoproj/argo-cd/v3/util/io"
- "github.com/argoproj/argo-cd/v3/util/templates"
+ "github.com/argoproj/argo-cd/v2/cmd/argocd/commands/admin"
+ "github.com/argoproj/argo-cd/v2/cmd/argocd/commands/headless"
+ "github.com/argoproj/argo-cd/v2/cmd/argocd/commands/utils"
+ cmdutil "github.com/argoproj/argo-cd/v2/cmd/util"
+ argocdclient "github.com/argoproj/argo-cd/v2/pkg/apiclient"
+ "github.com/argoproj/argo-cd/v2/pkg/apiclient/applicationset"
+ arogappsetv1 "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/grpc"
+ argoio "github.com/argoproj/argo-cd/v2/util/io"
+ "github.com/argoproj/argo-cd/v2/util/templates"
)
var appSetExample = templates.Examples(`
@@ -80,7 +80,7 @@ func NewApplicationSetGetCommand(clientOpts *argocdclient.ClientOptions) *cobra.
}
acdClient := headless.NewClientOrDie(clientOpts, c)
conn, appIf := acdClient.NewApplicationSetClientOrDie()
- defer utilio.Close(conn)
+ defer argoio.Close(conn)
appSetName, appSetNs := argo.ParseFromQualifiedName(args[0], "")
@@ -135,8 +135,8 @@ func NewApplicationSetCreateCommand(clientOpts *argocdclient.ClientOptions) *cob
os.Exit(1)
}
argocdClient := headless.NewClientOrDie(clientOpts, c)
- fileURL := args[0]
- appsets, err := cmdutil.ConstructApplicationSet(fileURL)
+ fileUrl := args[0]
+ appsets, err := cmdutil.ConstructApplicationSet(fileUrl)
errors.CheckError(err)
if len(appsets) == 0 {
@@ -146,11 +146,12 @@ func NewApplicationSetCreateCommand(clientOpts *argocdclient.ClientOptions) *cob
for _, appset := range appsets {
if appset.Name == "" {
- errors.Fatal(errors.ErrorGeneric, fmt.Sprintf("Error creating ApplicationSet %s. ApplicationSet does not have Name field set", appset))
+ err := fmt.Errorf("Error creating ApplicationSet %s. ApplicationSet does not have Name field set", appset)
+ errors.CheckError(err)
}
conn, appIf := argocdClient.NewApplicationSetClientOrDie()
- defer utilio.Close(conn)
+ defer argoio.Close(conn)
// Get app before creating to see if it is being updated or no change
existing, err := appIf.Get(ctx, &applicationset.ApplicationSetGetQuery{Name: appset.Name, AppsetNamespace: appset.Namespace})
@@ -172,16 +173,15 @@ func NewApplicationSetCreateCommand(clientOpts *argocdclient.ClientOptions) *cob
}
var action string
- switch {
- case existing == nil:
+ if existing == nil {
action = "created"
- case !hasAppSetChanged(existing, created, upsert):
+ } else if !hasAppSetChanged(existing, created, upsert) {
action = "unchanged"
- default:
+ } else {
action = "updated"
}
- c.PrintErrf("ApplicationSet '%s' %s%s\n", created.Name, action, dryRunMsg)
+ c.PrintErrf("ApplicationSet '%s' %s%s\n", created.ObjectMeta.Name, action, dryRunMsg)
switch output {
case "yaml", "json":
@@ -227,8 +227,8 @@ func NewApplicationSetGenerateCommand(clientOpts *argocdclient.ClientOptions) *c
os.Exit(1)
}
argocdClient := headless.NewClientOrDie(clientOpts, c)
- fileURL := args[0]
- appsets, err := cmdutil.ConstructApplicationSet(fileURL)
+ fileUrl := args[0]
+ appsets, err := cmdutil.ConstructApplicationSet(fileUrl)
errors.CheckError(err)
if len(appsets) != 1 {
@@ -237,11 +237,12 @@ func NewApplicationSetGenerateCommand(clientOpts *argocdclient.ClientOptions) *c
}
appset := appsets[0]
if appset.Name == "" {
- errors.Fatal(errors.ErrorGeneric, fmt.Sprintf("Error generating apps for ApplicationSet %s. ApplicationSet does not have Name field set", appset))
+ err := fmt.Errorf("Error generating apps for ApplicationSet %s. ApplicationSet does not have Name field set", appset)
+ errors.CheckError(err)
}
conn, appIf := argocdClient.NewApplicationSetClientOrDie()
- defer utilio.Close(conn)
+ defer argoio.Close(conn)
req := applicationset.ApplicationSetGenerateRequest{
ApplicationSet: appset,
@@ -256,7 +257,7 @@ func NewApplicationSetGenerateCommand(clientOpts *argocdclient.ClientOptions) *c
switch output {
case "yaml", "json":
- var resources []any
+ var resources []interface{}
for i := range appsList {
app := appsList[i]
// backfill api version and kind because k8s client always return empty values for these fields
@@ -292,11 +293,11 @@ func NewApplicationSetListCommand(clientOpts *argocdclient.ClientOptions) *cobra
# List all ApplicationSets
argocd appset list
`),
- Run: func(c *cobra.Command, _ []string) {
+ Run: func(c *cobra.Command, args []string) {
ctx := c.Context()
conn, appIf := headless.NewClientOrDie(clientOpts, c).NewApplicationSetClientOrDie()
- defer utilio.Close(conn)
+ defer argoio.Close(conn)
appsets, err := appIf.List(ctx, &applicationset.ApplicationSetListQuery{Selector: selector, Projects: projects, AppsetNamespace: appSetNamespace})
errors.CheckError(err)
@@ -341,8 +342,8 @@ func NewApplicationSetDeleteCommand(clientOpts *argocdclient.ClientOptions) *cob
os.Exit(1)
}
conn, appIf := headless.NewClientOrDie(clientOpts, c).NewApplicationSetClientOrDie()
- defer utilio.Close(conn)
- isTerminal := isatty.IsTerminal(os.Stdout.Fd()) || isatty.IsCygwinTerminal(os.Stdout.Fd())
+ defer argoio.Close(conn)
+ var isTerminal bool = isatty.IsTerminal(os.Stdout.Fd()) || isatty.IsCygwinTerminal(os.Stdout.Fd())
numOfApps := len(args)
promptFlag := c.Flag("yes")
if promptFlag.Changed && promptFlag.Value.String() == "true" {
@@ -395,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 := []any{"NAME", "PROJECT", "SYNCPOLICY", "CONDITIONS"}
+ headers := []interface{}{"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")
@@ -410,7 +411,7 @@ func printApplicationSetTable(apps []arogappsetv1.ApplicationSet, output *string
conditions = append(conditions, condition)
}
}
- vals := []any{
+ vals := []interface{}{
app.QualifiedName(),
app.Spec.Template.Spec.Project,
app.Spec.SyncPolicy,
@@ -458,7 +459,7 @@ func printAppSetSummaryTable(appSet *arogappsetv1.ApplicationSet) {
syncPolicyStr string
syncPolicy = appSet.Spec.Template.Spec.SyncPolicy
)
- if syncPolicy != nil && syncPolicy.IsAutomatedSyncEnabled() {
+ if syncPolicy != nil && syncPolicy.Automated != nil {
syncPolicyStr = "Automated"
if syncPolicy.Automated.Prune {
syncPolicyStr += " (Prune)"
@@ -495,7 +496,7 @@ func hasAppSetChanged(appReq, appRes *arogappsetv1.ApplicationSet, upsert bool)
if reflect.DeepEqual(appRes.Spec, appReq.Spec) &&
reflect.DeepEqual(appRes.Labels, appReq.Labels) &&
- reflect.DeepEqual(appRes.Annotations, appReq.Annotations) &&
+ reflect.DeepEqual(appRes.ObjectMeta.Annotations, appReq.Annotations) &&
reflect.DeepEqual(appRes.Finalizers, appReq.Finalizers) {
return false
}
diff --git a/cmd/argocd/commands/applicationset_test.go b/cmd/argocd/commands/applicationset_test.go
index c44f2297a5..fd6f07b5d7 100644
--- a/cmd/argocd/commands/applicationset_test.go
+++ b/cmd/argocd/commands/applicationset_test.go
@@ -9,7 +9,7 @@ import (
"github.com/stretchr/testify/require"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
)
func TestPrintApplicationSetNames(t *testing.T) {
diff --git a/cmd/argocd/commands/bcrypt.go b/cmd/argocd/commands/bcrypt.go
index 7b0b1a75af..d2557ef411 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, _ []string) {
+ Run: func(cmd *cobra.Command, args []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 3cd9b3b21c..d123a9ae66 100644
--- a/cmd/argocd/commands/cert.go
+++ b/cmd/argocd/commands/cert.go
@@ -2,7 +2,6 @@ package commands
import (
"crypto/x509"
- stderrors "errors"
"fmt"
"os"
"sort"
@@ -11,14 +10,14 @@ import (
"github.com/spf13/cobra"
- "github.com/argoproj/argo-cd/v3/cmd/argocd/commands/headless"
- "github.com/argoproj/argo-cd/v3/cmd/argocd/commands/utils"
- argocdclient "github.com/argoproj/argo-cd/v3/pkg/apiclient"
- certificatepkg "github.com/argoproj/argo-cd/v3/pkg/apiclient/certificate"
- appsv1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- certutil "github.com/argoproj/argo-cd/v3/util/cert"
- "github.com/argoproj/argo-cd/v3/util/errors"
- utilio "github.com/argoproj/argo-cd/v3/util/io"
+ "github.com/argoproj/argo-cd/v2/cmd/argocd/commands/headless"
+ "github.com/argoproj/argo-cd/v2/cmd/argocd/commands/utils"
+ argocdclient "github.com/argoproj/argo-cd/v2/pkg/apiclient"
+ certificatepkg "github.com/argoproj/argo-cd/v2/pkg/apiclient/certificate"
+ appsv1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+ certutil "github.com/argoproj/argo-cd/v2/util/cert"
+ "github.com/argoproj/argo-cd/v2/util/errors"
+ "github.com/argoproj/argo-cd/v2/util/io"
)
// NewCertCommand returns a new instance of an `argocd repo` command
@@ -69,7 +68,7 @@ func NewCertAddTLSCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command
ctx := c.Context()
conn, certIf := headless.NewClientOrDie(clientOpts, c).NewCertClientOrDie()
- defer utilio.Close(conn)
+ defer io.Close(conn)
if len(args) != 1 {
c.HelpFunc()(c, args)
@@ -106,8 +105,9 @@ 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]
@@ -148,11 +148,11 @@ 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, _ []string) {
+ Run: func(c *cobra.Command, args []string) {
ctx := c.Context()
conn, certIf := headless.NewClientOrDie(clientOpts, c).NewCertClientOrDie()
- defer utilio.Close(conn)
+ defer io.Close(conn)
var sshKnownHostsLists []string
var err error
@@ -167,13 +167,13 @@ func NewCertAddSSHCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command
sshKnownHostsLists, err = certutil.ParseSSHKnownHostsFromStream(os.Stdin)
}
} else {
- err = stderrors.New("you need to specify --batch or specify --help for usage instructions")
+ err = fmt.Errorf("You need to specify --batch or specify --help for usage instructions")
}
errors.CheckError(err)
if len(sshKnownHostsLists) == 0 {
- errors.Fatal(errors.ErrorGeneric, "No valid SSH known hosts data found.")
+ errors.CheckError(fmt.Errorf("No valid SSH known hosts data found."))
}
for _, knownHostsEntry := range sshKnownHostsLists {
@@ -226,7 +226,7 @@ func NewCertRemoveCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command
os.Exit(1)
}
conn, certIf := headless.NewClientOrDie(clientOpts, c).NewCertClientOrDie()
- defer utilio.Close(conn)
+ defer io.Close(conn)
hostNamePattern := args[0]
// Prevent the user from specifying a wildcard as hostname as precaution
@@ -234,7 +234,8 @@ func NewCertRemoveCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command
// remove all certificates, but it's less likely that it happens by
// accident.
if hostNamePattern == "*" {
- errors.Fatal(errors.ErrorGeneric, "A single wildcard is not allowed as REPOSERVER name.")
+ err := fmt.Errorf("A single wildcard is not allowed as REPOSERVER name.")
+ errors.CheckError(err)
}
promptUtil := utils.NewPrompt(clientOpts.PromptsEnabled)
@@ -275,7 +276,7 @@ func NewCertListCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command {
command := &cobra.Command{
Use: "list",
Short: "List configured certificates",
- Run: func(c *cobra.Command, _ []string) {
+ Run: func(c *cobra.Command, args []string) {
ctx := c.Context()
if certType != "" {
@@ -289,7 +290,7 @@ func NewCertListCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command {
}
conn, certIf := headless.NewClientOrDie(clientOpts, c).NewCertClientOrDie()
- defer utilio.Close(conn)
+ defer io.Close(conn)
certificates, err := certIf.ListCertificates(ctx, &certificatepkg.RepositoryCertificateQuery{HostNamePattern: hostNamePattern, CertType: certType})
errors.CheckError(err)
@@ -317,12 +318,11 @@ func printCertTable(certs []appsv1.RepositoryCertificate, sortOrder string) {
w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
fmt.Fprintf(w, "HOSTNAME\tTYPE\tSUBTYPE\tINFO\n")
- switch sortOrder {
- case "hostname", "":
+ if sortOrder == "hostname" || sortOrder == "" {
sort.Slice(certs, func(i, j int) bool {
return certs[i].ServerName < certs[j].ServerName
})
- case "type":
+ } else if sortOrder == "type" {
sort.Slice(certs, func(i, j int) bool {
return certs[i].CertType < certs[j].CertType
})
diff --git a/cmd/argocd/commands/cluster.go b/cmd/argocd/commands/cluster.go
index e41a8f8e6d..65a3981dab 100644
--- a/cmd/argocd/commands/cluster.go
+++ b/cmd/argocd/commands/cluster.go
@@ -8,9 +8,6 @@ import (
"strings"
"text/tabwriter"
- "google.golang.org/grpc/codes"
- "google.golang.org/grpc/status"
-
"github.com/mattn/go-isatty"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
@@ -18,17 +15,17 @@ import (
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
- "github.com/argoproj/argo-cd/v3/cmd/argocd/commands/headless"
- cmdutil "github.com/argoproj/argo-cd/v3/cmd/util"
- "github.com/argoproj/argo-cd/v3/common"
- argocdclient "github.com/argoproj/argo-cd/v3/pkg/apiclient"
- clusterpkg "github.com/argoproj/argo-cd/v3/pkg/apiclient/cluster"
- argoappv1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- "github.com/argoproj/argo-cd/v3/util/cli"
- "github.com/argoproj/argo-cd/v3/util/clusterauth"
- "github.com/argoproj/argo-cd/v3/util/errors"
- utilio "github.com/argoproj/argo-cd/v3/util/io"
- "github.com/argoproj/argo-cd/v3/util/text/label"
+ "github.com/argoproj/argo-cd/v2/cmd/argocd/commands/headless"
+ cmdutil "github.com/argoproj/argo-cd/v2/cmd/util"
+ "github.com/argoproj/argo-cd/v2/common"
+ argocdclient "github.com/argoproj/argo-cd/v2/pkg/apiclient"
+ clusterpkg "github.com/argoproj/argo-cd/v2/pkg/apiclient/cluster"
+ argoappv1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/util/cli"
+ "github.com/argoproj/argo-cd/v2/util/clusterauth"
+ "github.com/argoproj/argo-cd/v2/util/errors"
+ "github.com/argoproj/argo-cd/v2/util/io"
+ "github.com/argoproj/argo-cd/v2/util/text/label"
)
const (
@@ -91,7 +88,7 @@ func NewClusterAddCommand(clientOpts *argocdclient.ClientOptions, pathOpts *clie
)
command := &cobra.Command{
Use: "add CONTEXT",
- Short: cliName + " cluster add CONTEXT",
+ Short: fmt.Sprintf("%s cluster add CONTEXT", cliName),
Run: func(c *cobra.Command, args []string) {
ctx := c.Context()
@@ -120,14 +117,13 @@ func NewClusterAddCommand(clientOpts *argocdclient.ClientOptions, pathOpts *clie
managerBearerToken := ""
var awsAuthConf *argoappv1.AWSAuthConfig
var execProviderConf *argoappv1.ExecProviderConfig
- switch {
- case clusterOpts.AwsClusterName != "":
+ if clusterOpts.AwsClusterName != "" {
awsAuthConf = &argoappv1.AWSAuthConfig{
ClusterName: clusterOpts.AwsClusterName,
RoleARN: clusterOpts.AwsRoleArn,
Profile: clusterOpts.AwsProfile,
}
- case clusterOpts.ExecProviderCommand != "":
+ } else if clusterOpts.ExecProviderCommand != "" {
execProviderConf = &argoappv1.ExecProviderConfig{
Command: clusterOpts.ExecProviderCommand,
Args: clusterOpts.ExecProviderArgs,
@@ -135,7 +131,7 @@ func NewClusterAddCommand(clientOpts *argocdclient.ClientOptions, pathOpts *clie
APIVersion: clusterOpts.ExecProviderAPIVersion,
InstallHint: clusterOpts.ExecProviderInstallHint,
}
- default:
+ } else {
// Install RBAC resources for managing the cluster
if clusterOpts.ServiceAccount != "" {
managerBearerToken, err = clusterauth.GetServiceAccountBearerToken(clientset, clusterOpts.SystemNamespace, clusterOpts.ServiceAccount, common.BearerTokenTimeout)
@@ -162,7 +158,7 @@ func NewClusterAddCommand(clientOpts *argocdclient.ClientOptions, pathOpts *clie
errors.CheckError(err)
conn, clusterIf := headless.NewClientOrDie(clientOpts, c).NewClusterClientOrDie()
- defer utilio.Close(conn)
+ defer io.Close(conn)
if clusterOpts.Name != "" {
contextName = clusterOpts.Name
}
@@ -170,14 +166,13 @@ func NewClusterAddCommand(clientOpts *argocdclient.ClientOptions, pathOpts *clie
if clusterOpts.InClusterEndpoint() {
clst.Server = argoappv1.KubernetesInternalAPIServerAddr
} else if clusterOpts.ClusterEndpoint == string(cmdutil.KubePublicEndpoint) {
- endpoint, caData, err := cmdutil.GetKubePublicEndpoint(clientset)
+ endpoint, err := cmdutil.GetKubePublicEndpoint(clientset)
if err != nil || len(endpoint) == 0 {
log.Warnf("Failed to find the cluster endpoint from kube-public data: %v", err)
log.Infof("Falling back to the endpoint '%s' as listed in the kubeconfig context", clst.Server)
endpoint = clst.Server
}
clst.Server = endpoint
- clst.Config.CAData = caData
}
if clusterOpts.Shard >= 0 {
@@ -215,7 +210,7 @@ func getRestConfig(pathOpts *clientcmd.PathOptions, ctxName string) (*rest.Confi
clstContext := config.Contexts[ctxName]
if clstContext == nil {
- return nil, fmt.Errorf("context %s does not exist in kubeconfig", ctxName)
+ return nil, fmt.Errorf("Context %s does not exist in kubeconfig", ctxName)
}
overrides := clientcmd.ConfigOverrides{
@@ -254,7 +249,7 @@ func NewClusterSetCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command
// name of the cluster whose fields have to be updated.
clusterName = args[0]
conn, clusterIf := headless.NewClientOrDie(clientOpts, c).NewClusterClientOrDie()
- defer utilio.Close(conn)
+ defer io.Close(conn)
// checks the fields that needs to be updated
updatedFields := checkFieldsToUpdate(clusterOptions, labels, annotations)
namespaces := clusterOptions.Namespaces
@@ -283,12 +278,7 @@ func NewClusterSetCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command
},
}
_, err := clusterIf.Update(ctx, &clusterUpdateRequest)
- if err != nil {
- if status.Code(err) == codes.PermissionDenied {
- log.Error("Ensure that the cluster is present and you have the necessary permissions to update the cluster")
- }
- errors.CheckError(err)
- }
+ errors.CheckError(err)
fmt.Printf("Cluster '%s' updated.\n", clusterName)
} else {
fmt.Print("Specify the cluster field to be updated.\n")
@@ -336,7 +326,7 @@ argocd cluster get in-cluster`,
os.Exit(1)
}
conn, clusterIf := headless.NewClientOrDie(clientOpts, c).NewClusterClientOrDie()
- defer utilio.Close(conn)
+ defer io.Close(conn)
clusters := make([]argoappv1.Cluster, 0)
for _, clusterSelector := range args {
clst, err := clusterIf.Get(ctx, getQueryBySelector(clusterSelector))
@@ -380,12 +370,12 @@ func printClusterDetails(clusters []argoappv1.Cluster) {
fmt.Printf("Cluster information\n\n")
fmt.Printf(" Server URL: %s\n", cluster.Server)
fmt.Printf(" Server Name: %s\n", strWithDefault(cluster.Name, "-"))
- //nolint:staticcheck
+ // nolint:staticcheck
fmt.Printf(" Server Version: %s\n", cluster.ServerVersion)
fmt.Printf(" Namespaces: %s\n", formatNamespaces(cluster))
fmt.Printf("\nTLS configuration\n\n")
- fmt.Printf(" Client cert: %v\n", string(cluster.Config.CertData) != "")
- fmt.Printf(" Cert validation: %v\n", !cluster.Config.Insecure)
+ fmt.Printf(" Client cert: %v\n", string(cluster.Config.TLSClientConfig.CertData) != "")
+ fmt.Printf(" Cert validation: %v\n", !cluster.Config.TLSClientConfig.Insecure)
fmt.Printf("\nAuthentication\n\n")
fmt.Printf(" Basic authentication: %v\n", cluster.Config.Username != "")
fmt.Printf(" oAuth authentication: %v\n", cluster.Config.BearerToken != "")
@@ -412,9 +402,9 @@ argocd cluster rm cluster-name`,
os.Exit(1)
}
conn, clusterIf := headless.NewClientOrDie(clientOpts, c).NewClusterClientOrDie()
- defer utilio.Close(conn)
+ defer io.Close(conn)
numOfClusters := len(args)
- var isConfirmAll bool
+ var isConfirmAll bool = false
for _, clusterSelector := range args {
clusterQuery := getQueryBySelector(clusterSelector)
@@ -475,7 +465,7 @@ func printClusterTable(clusters []argoappv1.Cluster) {
if len(c.Namespaces) > 0 {
server = fmt.Sprintf("%s (%d namespaces)", c.Server, len(c.Namespaces))
}
- //nolint:staticcheck
+ // nolint:staticcheck
_, _ = fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\t%s\n", server, c.Name, c.ServerVersion, c.ConnectionState.Status, c.ConnectionState.Message, c.Project)
}
_ = w.Flush()
@@ -506,11 +496,11 @@ func NewClusterListCommand(clientOpts *argocdclient.ClientOptions) *cobra.Comman
command := &cobra.Command{
Use: "list",
Short: "List configured clusters",
- Run: func(c *cobra.Command, _ []string) {
+ Run: func(c *cobra.Command, args []string) {
ctx := c.Context()
conn, clusterIf := headless.NewClientOrDie(clientOpts, c).NewClusterClientOrDie()
- defer utilio.Close(conn)
+ defer io.Close(conn)
clusters, err := clusterIf.List(ctx, &clusterpkg.ClusterQuery{})
errors.CheckError(err)
switch output {
@@ -551,7 +541,7 @@ argocd cluster list -o server
func NewClusterRotateAuthCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command {
command := &cobra.Command{
Use: "rotate-auth SERVER/NAME",
- Short: cliName + " cluster rotate-auth SERVER/NAME",
+ Short: fmt.Sprintf("%s cluster rotate-auth SERVER/NAME", cliName),
Example: `argocd cluster rotate-auth https://12.34.567.89
argocd cluster rotate-auth cluster-name`,
Run: func(c *cobra.Command, args []string) {
@@ -562,7 +552,7 @@ argocd cluster rotate-auth cluster-name`,
os.Exit(1)
}
conn, clusterIf := headless.NewClientOrDie(clientOpts, c).NewClusterClientOrDie()
- defer utilio.Close(conn)
+ defer io.Close(conn)
cluster := args[0]
clusterQuery := getQueryBySelector(cluster)
diff --git a/cmd/argocd/commands/cluster_test.go b/cmd/argocd/commands/cluster_test.go
index 8307f36428..311713a30f 100644
--- a/cmd/argocd/commands/cluster_test.go
+++ b/cmd/argocd/commands/cluster_test.go
@@ -9,24 +9,24 @@ import (
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
)
func Test_getQueryBySelector(t *testing.T) {
query := getQueryBySelector("my-cluster")
assert.Equal(t, "my-cluster", query.Name)
- assert.Empty(t, query.Server)
+ assert.Equal(t, "", query.Server)
query = getQueryBySelector("http://my-server")
- assert.Empty(t, query.Name)
+ assert.Equal(t, "", query.Name)
assert.Equal(t, "http://my-server", query.Server)
query = getQueryBySelector("https://my-server")
- assert.Empty(t, query.Name)
+ assert.Equal(t, "", query.Name)
assert.Equal(t, "https://my-server", query.Server)
}
-func Test_printClusterTable(_ *testing.T) {
+func Test_printClusterTable(t *testing.T) {
printClusterTable([]v1alpha1.Cluster{
{
Server: "my-server",
@@ -93,7 +93,7 @@ func Test_getRestConfig(t *testing.T) {
},
nil,
true,
- "context not-exist does not exist in kubeconfig",
+ "Context not-exist does not exist in kubeconfig",
},
}
for _, tt := range tests {
diff --git a/cmd/argocd/commands/common.go b/cmd/argocd/commands/common.go
index 9b924e063b..849b9a48f0 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 any, output string) error {
+func PrintResource(resource interface{}, output string) error {
switch output {
case "json":
jsonBytes, err := json.MarshalIndent(resource, "", " ")
@@ -38,7 +38,7 @@ func PrintResource(resource any, output string) error {
}
// PrintResourceList marshals & prints a list of resources to stdout according to the output format
-func PrintResourceList(resources any, output string, single bool) error {
+func PrintResourceList(resources interface{}, 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/common_test.go b/cmd/argocd/commands/common_test.go
index 8e0834253a..8a3a2446a6 100644
--- a/cmd/argocd/commands/common_test.go
+++ b/cmd/argocd/commands/common_test.go
@@ -16,7 +16,7 @@ baz: foo
foo: bar
`
-const expectJSONSingle = `{
+const expectJsonSingle = `{
"bar": "",
"baz": "foo",
"foo": "bar"
@@ -33,7 +33,7 @@ two:
foo: bar
`
-const expectJSONList = `{
+const expectJsonList = `{
"one": {
"bar": "",
"baz": "foo",
@@ -88,7 +88,7 @@ func Test_PrintResource(t *testing.T) {
return err
})
require.NoError(t, err)
- assert.JSONEq(t, expectJSONSingle, str)
+ assert.JSONEq(t, expectJsonSingle, str)
err = PrintResource(testResource, "unknown")
require.Error(t, err)
@@ -123,7 +123,7 @@ func Test_PrintResourceList(t *testing.T) {
return err
})
require.NoError(t, err)
- assert.JSONEq(t, expectJSONList, str)
+ assert.JSONEq(t, expectJsonList, str)
str, err = captureOutput(func() error {
err := PrintResourceList(testResource2, "yaml", true)
@@ -137,7 +137,7 @@ func Test_PrintResourceList(t *testing.T) {
return err
})
require.NoError(t, err)
- assert.JSONEq(t, expectJSONSingle, str)
+ assert.JSONEq(t, expectJsonSingle, str)
err = PrintResourceList(testResource, "unknown", false)
require.Error(t, err)
diff --git a/cmd/argocd/commands/configure.go b/cmd/argocd/commands/configure.go
index d5fa4f2a2d..15c4bef41e 100644
--- a/cmd/argocd/commands/configure.go
+++ b/cmd/argocd/commands/configure.go
@@ -6,9 +6,9 @@ import (
"github.com/spf13/cobra"
- argocdclient "github.com/argoproj/argo-cd/v3/pkg/apiclient"
- "github.com/argoproj/argo-cd/v3/util/errors"
- "github.com/argoproj/argo-cd/v3/util/localconfig"
+ argocdclient "github.com/argoproj/argo-cd/v2/pkg/apiclient"
+ "github.com/argoproj/argo-cd/v2/util/errors"
+ "github.com/argoproj/argo-cd/v2/util/localconfig"
)
// NewConfigureCommand returns a new instance of an `argocd configure` command
@@ -24,7 +24,7 @@ argocd configure --prompts-enabled=true
# Disable optional interactive prompts
argocd configure --prompts-enabled=false`,
- Run: func(_ *cobra.Command, _ []string) {
+ Run: func(c *cobra.Command, args []string) {
localCfg, err := localconfig.ReadLocalConfig(globalClientOpts.ConfigPath)
errors.CheckError(err)
diff --git a/cmd/argocd/commands/configure_test.go b/cmd/argocd/commands/configure_test.go
index a538ffb225..cb084f88ab 100644
--- a/cmd/argocd/commands/configure_test.go
+++ b/cmd/argocd/commands/configure_test.go
@@ -4,12 +4,12 @@ import (
"os"
"testing"
- argocdclient "github.com/argoproj/argo-cd/v3/pkg/apiclient"
+ argocdclient "github.com/argoproj/argo-cd/v2/pkg/apiclient"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
- "github.com/argoproj/argo-cd/v3/util/localconfig"
+ "github.com/argoproj/argo-cd/v2/util/localconfig"
)
func TestNewConfigureCommand_PromptsEnabled_DefaultTrue(t *testing.T) {
diff --git a/cmd/argocd/commands/context.go b/cmd/argocd/commands/context.go
index 38be5e8808..2c4b37ba2f 100644
--- a/cmd/argocd/commands/context.go
+++ b/cmd/argocd/commands/context.go
@@ -1,7 +1,6 @@
package commands
import (
- stderrors "errors"
"fmt"
"os"
"path"
@@ -11,9 +10,9 @@ import (
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
- argocdclient "github.com/argoproj/argo-cd/v3/pkg/apiclient"
- "github.com/argoproj/argo-cd/v3/util/errors"
- "github.com/argoproj/argo-cd/v3/util/localconfig"
+ argocdclient "github.com/argoproj/argo-cd/v2/pkg/apiclient"
+ "github.com/argoproj/argo-cd/v2/util/errors"
+ "github.com/argoproj/argo-cd/v2/util/localconfig"
)
// NewContextCommand returns a new instance of an `argocd ctx` command
@@ -86,12 +85,12 @@ func deleteContext(context, configPath string) error {
localCfg, err := localconfig.ReadLocalConfig(configPath)
errors.CheckError(err)
if localCfg == nil {
- return stderrors.New("nothing to logout from")
+ return fmt.Errorf("Nothing to logout from")
}
serverName, ok := localCfg.RemoveContext(context)
if !ok {
- return fmt.Errorf("context %s does not exist", context)
+ return fmt.Errorf("Context %s does not exist", context)
}
_ = localCfg.RemoveUser(context)
_ = localCfg.RemoveServer(serverName)
@@ -105,7 +104,7 @@ func deleteContext(context, configPath string) error {
}
err = localconfig.ValidateLocalConfig(*localCfg)
if err != nil {
- return stderrors.New("error in logging out")
+ return fmt.Errorf("Error in logging out")
}
err = localconfig.WriteLocalConfig(*localCfg, configPath)
errors.CheckError(err)
diff --git a/cmd/argocd/commands/context_test.go b/cmd/argocd/commands/context_test.go
index 0e31a3a7ec..e9f953a22c 100644
--- a/cmd/argocd/commands/context_test.go
+++ b/cmd/argocd/commands/context_test.go
@@ -7,7 +7,7 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
- "github.com/argoproj/argo-cd/v3/util/localconfig"
+ "github.com/argoproj/argo-cd/v2/util/localconfig"
)
const testConfig = `contexts:
@@ -70,7 +70,7 @@ func TestContextDelete(t *testing.T) {
localConfig, err = localconfig.ReadLocalConfig(testConfigFilePath)
require.NoError(t, err)
- assert.Empty(t, localConfig.CurrentContext)
+ assert.Equal(t, "", localConfig.CurrentContext)
assert.NotContains(t, localConfig.Contexts, localconfig.ContextRef{Name: "localhost:8080", Server: "localhost:8080", User: "localhost:8080"})
assert.NotContains(t, localConfig.Servers, localconfig.Server{PlainText: true, Server: "localhost:8080"})
assert.NotContains(t, localConfig.Users, localconfig.User{AuthToken: "vErrYS3c3tReFRe$hToken", Name: "localhost:8080"})
diff --git a/cmd/argocd/commands/gpg.go b/cmd/argocd/commands/gpg.go
index 3150c5cfe8..bc50655cfa 100644
--- a/cmd/argocd/commands/gpg.go
+++ b/cmd/argocd/commands/gpg.go
@@ -1,7 +1,6 @@
package commands
import (
- stderrors "errors"
"fmt"
"os"
"strings"
@@ -9,14 +8,14 @@ import (
"github.com/spf13/cobra"
- "github.com/argoproj/argo-cd/v3/cmd/argocd/commands/headless"
- "github.com/argoproj/argo-cd/v3/cmd/argocd/commands/utils"
- argocdclient "github.com/argoproj/argo-cd/v3/pkg/apiclient"
- gpgkeypkg "github.com/argoproj/argo-cd/v3/pkg/apiclient/gpgkey"
- appsv1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- "github.com/argoproj/argo-cd/v3/util/errors"
- utilio "github.com/argoproj/argo-cd/v3/util/io"
- "github.com/argoproj/argo-cd/v3/util/templates"
+ "github.com/argoproj/argo-cd/v2/cmd/argocd/commands/headless"
+ "github.com/argoproj/argo-cd/v2/cmd/argocd/commands/utils"
+ argocdclient "github.com/argoproj/argo-cd/v2/pkg/apiclient"
+ gpgkeypkg "github.com/argoproj/argo-cd/v2/pkg/apiclient/gpgkey"
+ appsv1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/util/errors"
+ argoio "github.com/argoproj/argo-cd/v2/util/io"
+ "github.com/argoproj/argo-cd/v2/util/templates"
)
// NewGPGCommand returns a new instance of an `argocd repo` command
@@ -54,11 +53,11 @@ func NewGPGListCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command {
argocd gpg list -o yaml
`),
- Run: func(c *cobra.Command, _ []string) {
+ Run: func(c *cobra.Command, args []string) {
ctx := c.Context()
conn, gpgIf := headless.NewClientOrDie(clientOpts, c).NewGPGKeyClientOrDie()
- defer utilio.Close(conn)
+ defer argoio.Close(conn)
keys, err := gpgIf.List(ctx, &gpgkeypkg.GnuPGPublicKeyQuery{})
errors.CheckError(err)
switch output {
@@ -97,10 +96,10 @@ func NewGPGGetCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command {
ctx := c.Context()
if len(args) != 1 {
- errors.Fatal(errors.ErrorGeneric, "Missing KEYID argument")
+ errors.CheckError(fmt.Errorf("Missing KEYID argument"))
}
conn, gpgIf := headless.NewClientOrDie(clientOpts, c).NewGPGKeyClientOrDie()
- defer utilio.Close(conn)
+ defer argoio.Close(conn)
key, err := gpgIf.Get(ctx, &gpgkeypkg.GnuPGPublicKeyQuery{KeyID: args[0]})
errors.CheckError(err)
switch output {
@@ -133,18 +132,18 @@ func NewGPGAddCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command {
argocd gpg add --from /path/to/keyfile
`),
- Run: func(c *cobra.Command, _ []string) {
+ Run: func(c *cobra.Command, args []string) {
ctx := c.Context()
if fromFile == "" {
- errors.CheckError(stderrors.New("--from is mandatory"))
+ errors.CheckError(fmt.Errorf("--from is mandatory"))
}
keyData, err := os.ReadFile(fromFile)
if err != nil {
errors.CheckError(err)
}
conn, gpgIf := headless.NewClientOrDie(clientOpts, c).NewGPGKeyClientOrDie()
- defer utilio.Close(conn)
+ defer argoio.Close(conn)
resp, err := gpgIf.Create(ctx, &gpgkeypkg.GnuPGPublicKeyCreateRequest{Publickey: &appsv1.GnuPGPublicKey{KeyData: string(keyData)}})
errors.CheckError(err)
fmt.Printf("Created %d key(s) from input file", len(resp.Created.Items))
@@ -167,13 +166,13 @@ func NewGPGDeleteCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command
ctx := c.Context()
if len(args) != 1 {
- errors.Fatal(errors.ErrorGeneric, "Missing KEYID argument")
+ errors.CheckError(fmt.Errorf("Missing KEYID argument"))
}
keyId := args[0]
conn, gpgIf := headless.NewClientOrDie(clientOpts, c).NewGPGKeyClientOrDie()
- defer utilio.Close(conn)
+ defer argoio.Close(conn)
promptUtil := utils.NewPrompt(clientOpts.PromptsEnabled)
canDelete := promptUtil.Confirm(fmt.Sprintf("Are you sure you want to remove '%s'? [y/n] ", keyId))
diff --git a/cmd/argocd/commands/headless/headless.go b/cmd/argocd/commands/headless/headless.go
index 07630b406f..64505fd9c0 100644
--- a/cmd/argocd/commands/headless/headless.go
+++ b/cmd/argocd/commands/headless/headless.go
@@ -15,7 +15,7 @@ import (
"github.com/spf13/cobra"
"github.com/spf13/pflag"
corev1 "k8s.io/api/core/v1"
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+ metaV1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
runtimeUtil "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/client-go/dynamic"
@@ -25,20 +25,20 @@ import (
"k8s.io/utils/ptr"
"sigs.k8s.io/controller-runtime/pkg/client"
- "github.com/argoproj/argo-cd/v3/cmd/argocd/commands/initialize"
- "github.com/argoproj/argo-cd/v3/common"
- "github.com/argoproj/argo-cd/v3/pkg/apiclient"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- appclientset "github.com/argoproj/argo-cd/v3/pkg/client/clientset/versioned"
- repoapiclient "github.com/argoproj/argo-cd/v3/reposerver/apiclient"
- "github.com/argoproj/argo-cd/v3/server"
- servercache "github.com/argoproj/argo-cd/v3/server/cache"
- "github.com/argoproj/argo-cd/v3/util/cache"
- appstatecache "github.com/argoproj/argo-cd/v3/util/cache/appstate"
- "github.com/argoproj/argo-cd/v3/util/cli"
- utilio "github.com/argoproj/argo-cd/v3/util/io"
- kubeutil "github.com/argoproj/argo-cd/v3/util/kube"
- "github.com/argoproj/argo-cd/v3/util/localconfig"
+ "github.com/argoproj/argo-cd/v2/cmd/argocd/commands/initialize"
+ "github.com/argoproj/argo-cd/v2/common"
+ "github.com/argoproj/argo-cd/v2/pkg/apiclient"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+ appclientset "github.com/argoproj/argo-cd/v2/pkg/client/clientset/versioned"
+ repoapiclient "github.com/argoproj/argo-cd/v2/reposerver/apiclient"
+ "github.com/argoproj/argo-cd/v2/server"
+ servercache "github.com/argoproj/argo-cd/v2/server/cache"
+ "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/cli"
+ "github.com/argoproj/argo-cd/v2/util/io"
+ kubeutil "github.com/argoproj/argo-cd/v2/util/kube"
+ "github.com/argoproj/argo-cd/v2/util/localconfig"
)
type forwardCacheClient struct {
@@ -88,7 +88,7 @@ func (c *forwardCacheClient) Rename(oldKey string, newKey string, expiration tim
})
}
-func (c *forwardCacheClient) Get(key string, obj any) error {
+func (c *forwardCacheClient) Get(key string, obj interface{}) error {
return c.doLazy(func(client cache.CacheClient) error {
return client.Get(key, obj)
})
@@ -122,14 +122,14 @@ type forwardRepoClientset struct {
kubeClientset kubernetes.Interface
}
-func (c *forwardRepoClientset) NewRepoServerClient() (utilio.Closer, repoapiclient.RepoServerServiceClient, error) {
+func (c *forwardRepoClientset) NewRepoServerClient() (io.Closer, repoapiclient.RepoServerServiceClient, error) {
c.init.Do(func() {
overrides := clientcmd.ConfigOverrides{
CurrentContext: c.context,
}
repoServerName := c.repoServerName
repoServererviceLabelSelector := common.LabelKeyComponentRepoServer + "=" + common.LabelValueComponentRepoServer
- repoServerServices, err := c.kubeClientset.CoreV1().Services(c.namespace).List(context.Background(), metav1.ListOptions{LabelSelector: repoServererviceLabelSelector})
+ repoServerServices, err := c.kubeClientset.CoreV1().Services(c.namespace).List(context.Background(), metaV1.ListOptions{LabelSelector: repoServererviceLabelSelector})
if err != nil {
c.err = err
return
@@ -164,7 +164,7 @@ func testAPI(ctx context.Context, clientOpts *apiclient.ClientOptions) error {
if err != nil {
return fmt.Errorf("failed to create version client: %w", err)
}
- defer utilio.Close(closer)
+ defer io.Close(closer)
_, err = versionClient.Version(ctx, &empty.Empty{})
if err != nil {
return fmt.Errorf("failed to get version: %w", err)
@@ -212,13 +212,13 @@ func MaybeStartLocalServer(ctx context.Context, clientOpts *apiclient.ClientOpti
address = ptr.To("localhost")
}
if port == nil || *port == 0 {
- addr := *address + ":0"
+ addr := fmt.Sprintf("%s:0", *address)
ln, err := net.Listen("tcp", addr)
if err != nil {
return fmt.Errorf("failed to listen on %q: %w", addr, err)
}
port = &ln.Addr().(*net.TCPAddr).Port
- utilio.Close(ln)
+ io.Close(ln)
}
restConfig, err := clientConfig.ClientConfig()
diff --git a/cmd/argocd/commands/initialize/cmd.go b/cmd/argocd/commands/initialize/cmd.go
index 1cc0b45e06..8f9da9f687 100644
--- a/cmd/argocd/commands/initialize/cmd.go
+++ b/cmd/argocd/commands/initialize/cmd.go
@@ -4,7 +4,7 @@ import (
"github.com/spf13/cobra"
"github.com/spf13/pflag"
- "github.com/argoproj/argo-cd/v3/util/cli"
+ "github.com/argoproj/argo-cd/v2/util/cli"
)
func RetrieveContextIfChanged(contextFlag *pflag.Flag) string {
diff --git a/cmd/argocd/commands/initialize/cmd_test.go b/cmd/argocd/commands/initialize/cmd_test.go
index 597fc965cc..59f2efb55a 100644
--- a/cmd/argocd/commands/initialize/cmd_test.go
+++ b/cmd/argocd/commands/initialize/cmd_test.go
@@ -40,7 +40,7 @@ func Test_FlagContextNotChanged(t *testing.T) {
Annotations: nil,
})
- assert.Empty(t, res)
+ assert.Equal(t, "", res)
}
func Test_FlagContextChanged(t *testing.T) {
@@ -76,5 +76,5 @@ func Test_FlagContextNil(t *testing.T) {
Annotations: nil,
})
- assert.Empty(t, res)
+ assert.Equal(t, "", res)
}
diff --git a/cmd/argocd/commands/login.go b/cmd/argocd/commands/login.go
index 07854f2aaf..72b89dae17 100644
--- a/cmd/argocd/commands/login.go
+++ b/cmd/argocd/commands/login.go
@@ -13,25 +13,25 @@ import (
"time"
"github.com/coreos/go-oidc/v3/oidc"
- "github.com/golang-jwt/jwt/v5"
+ "github.com/golang-jwt/jwt/v4"
log "github.com/sirupsen/logrus"
"github.com/skratchdot/open-golang/open"
"github.com/spf13/cobra"
"golang.org/x/oauth2"
- "github.com/argoproj/argo-cd/v3/cmd/argocd/commands/headless"
- argocdclient "github.com/argoproj/argo-cd/v3/pkg/apiclient"
- sessionpkg "github.com/argoproj/argo-cd/v3/pkg/apiclient/session"
- settingspkg "github.com/argoproj/argo-cd/v3/pkg/apiclient/settings"
- claimsutil "github.com/argoproj/argo-cd/v3/util/claims"
- "github.com/argoproj/argo-cd/v3/util/cli"
- "github.com/argoproj/argo-cd/v3/util/errors"
- grpc_util "github.com/argoproj/argo-cd/v3/util/grpc"
- utilio "github.com/argoproj/argo-cd/v3/util/io"
- "github.com/argoproj/argo-cd/v3/util/localconfig"
- oidcutil "github.com/argoproj/argo-cd/v3/util/oidc"
- "github.com/argoproj/argo-cd/v3/util/rand"
- oidcconfig "github.com/argoproj/argo-cd/v3/util/settings"
+ "github.com/argoproj/argo-cd/v2/cmd/argocd/commands/headless"
+ argocdclient "github.com/argoproj/argo-cd/v2/pkg/apiclient"
+ sessionpkg "github.com/argoproj/argo-cd/v2/pkg/apiclient/session"
+ settingspkg "github.com/argoproj/argo-cd/v2/pkg/apiclient/settings"
+ "github.com/argoproj/argo-cd/v2/util/cli"
+ "github.com/argoproj/argo-cd/v2/util/errors"
+ grpc_util "github.com/argoproj/argo-cd/v2/util/grpc"
+ "github.com/argoproj/argo-cd/v2/util/io"
+ jwtutil "github.com/argoproj/argo-cd/v2/util/jwt"
+ "github.com/argoproj/argo-cd/v2/util/localconfig"
+ oidcutil "github.com/argoproj/argo-cd/v2/util/oidc"
+ "github.com/argoproj/argo-cd/v2/util/rand"
+ oidcconfig "github.com/argoproj/argo-cd/v2/util/settings"
)
// NewLoginCommand returns a new instance of `argocd login` command
@@ -67,12 +67,11 @@ argocd login cd.argoproj.io --core`,
os.Exit(1)
}
- switch {
- case globalClientOpts.PortForward:
+ if globalClientOpts.PortForward {
server = "port-forward"
- case globalClientOpts.Core:
+ } else if globalClientOpts.Core {
server = "kubernetes"
- default:
+ } else {
server = args[0]
if !skipTestTLS {
@@ -126,7 +125,7 @@ argocd login cd.argoproj.io --core`,
if !globalClientOpts.Core {
acdClient := headless.NewClientOrDie(&clientOpts, c)
setConn, setIf := acdClient.NewSettingsClientOrDie()
- defer utilio.Close(setConn)
+ defer io.Close(setConn)
if !sso {
tokenString = passwordLogin(ctx, acdClient, username, password)
} else {
@@ -143,9 +142,7 @@ argocd login cd.argoproj.io --core`,
claims := jwt.MapClaims{}
_, _, err := parser.ParseUnverified(tokenString, &claims)
errors.CheckError(err)
- argoClaims, err := claimsutil.MapClaimsToArgoClaims(claims)
- errors.CheckError(err)
- fmt.Printf("'%s' logged in successfully\n", userDisplayName(argoClaims))
+ fmt.Printf("'%s' logged in successfully\n", userDisplayName(claims))
}
// login successful. Persist the config
@@ -192,17 +189,14 @@ argocd login cd.argoproj.io --core`,
return command
}
-func userDisplayName(claims *claimsutil.ArgoClaims) string {
- if claims == nil {
- return ""
+func userDisplayName(claims jwt.MapClaims) string {
+ if email := jwtutil.StringField(claims, "email"); email != "" {
+ return email
}
- if claims.Email != "" {
- return claims.Email
+ if name := jwtutil.StringField(claims, "name"); name != "" {
+ return name
}
- if claims.Name != "" {
- return claims.Name
- }
- return claims.GetUserIdentifier()
+ return jwtutil.StringField(claims, "sub")
}
// oauth2Login opens a browser, runs a temporary HTTP server to delegate OAuth2 login flow and
@@ -360,7 +354,7 @@ func oauth2Login(
func passwordLogin(ctx context.Context, acdClient argocdclient.Client, username, password string) string {
username, password = cli.PromptCredentials(username, password)
sessConn, sessionIf := acdClient.NewSessionClientOrDie()
- defer utilio.Close(sessConn)
+ defer io.Close(sessConn)
sessionRequest := sessionpkg.SessionCreateRequest{
Username: username,
Password: password,
diff --git a/cmd/argocd/commands/login_test.go b/cmd/argocd/commands/login_test.go
index 43cbf1febf..420b484674 100644
--- a/cmd/argocd/commands/login_test.go
+++ b/cmd/argocd/commands/login_test.go
@@ -5,12 +5,10 @@ import (
"os"
"testing"
- claimsutil "github.com/argoproj/argo-cd/v3/util/claims"
- utilio "github.com/argoproj/argo-cd/v3/util/io"
+ utils "github.com/argoproj/argo-cd/v2/util/io"
- "github.com/golang-jwt/jwt/v5"
+ "github.com/golang-jwt/jwt/v4"
"github.com/stretchr/testify/assert"
- "github.com/stretchr/testify/require"
)
func captureStdout(callback func()) (string, error) {
@@ -27,7 +25,7 @@ func captureStdout(callback func()) (string, error) {
}()
callback()
- utilio.Close(w)
+ utils.Close(w)
data, err := io.ReadAll(r)
if err != nil {
@@ -37,45 +35,26 @@ func captureStdout(callback func()) (string, error) {
}
func Test_userDisplayName_email(t *testing.T) {
- claims, err := claimsutil.MapClaimsToArgoClaims(jwt.MapClaims{"iss": "qux", "sub": "foo", "email": "firstname.lastname@example.com", "groups": []string{"baz"}})
- require.NoError(t, err)
+ claims := jwt.MapClaims{"iss": "qux", "sub": "foo", "email": "firstname.lastname@example.com", "groups": []string{"baz"}}
actualName := userDisplayName(claims)
expectedName := "firstname.lastname@example.com"
assert.Equal(t, expectedName, actualName)
}
func Test_userDisplayName_name(t *testing.T) {
- claims, err := claimsutil.MapClaimsToArgoClaims(jwt.MapClaims{"iss": "qux", "sub": "foo", "name": "Firstname Lastname", "groups": []string{"baz"}})
- require.NoError(t, err)
+ claims := jwt.MapClaims{"iss": "qux", "sub": "foo", "name": "Firstname Lastname", "groups": []string{"baz"}}
actualName := userDisplayName(claims)
expectedName := "Firstname Lastname"
assert.Equal(t, expectedName, actualName)
}
func Test_userDisplayName_sub(t *testing.T) {
- claims, err := claimsutil.MapClaimsToArgoClaims(jwt.MapClaims{"iss": "qux", "sub": "foo", "groups": []string{"baz"}})
- require.NoError(t, err)
+ claims := jwt.MapClaims{"iss": "qux", "sub": "foo", "groups": []string{"baz"}}
actualName := userDisplayName(claims)
expectedName := "foo"
assert.Equal(t, expectedName, actualName)
}
-func Test_userDisplayName_federatedClaims(t *testing.T) {
- claims, err := claimsutil.MapClaimsToArgoClaims(jwt.MapClaims{
- "iss": "qux",
- "sub": "foo",
- "groups": []string{"baz"},
- "federated_claims": map[string]any{
- "connector_id": "dex",
- "user_id": "ldap-123",
- },
- })
- require.NoError(t, err)
- actualName := userDisplayName(claims)
- expectedName := "ldap-123"
- assert.Equal(t, expectedName, actualName)
-}
-
func Test_ssoAuthFlow_ssoLaunchBrowser_false(t *testing.T) {
out, _ := captureStdout(func() {
ssoAuthFlow("http://test-sso-browser-flow.com", false)
diff --git a/cmd/argocd/commands/logout.go b/cmd/argocd/commands/logout.go
index 4f39df8841..29dce70965 100644
--- a/cmd/argocd/commands/logout.go
+++ b/cmd/argocd/commands/logout.go
@@ -7,10 +7,10 @@ import (
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
- "github.com/argoproj/argo-cd/v3/cmd/argocd/commands/utils"
- argocdclient "github.com/argoproj/argo-cd/v3/pkg/apiclient"
- "github.com/argoproj/argo-cd/v3/util/errors"
- "github.com/argoproj/argo-cd/v3/util/localconfig"
+ "github.com/argoproj/argo-cd/v2/cmd/argocd/commands/utils"
+ argocdclient "github.com/argoproj/argo-cd/v2/pkg/apiclient"
+ "github.com/argoproj/argo-cd/v2/util/errors"
+ "github.com/argoproj/argo-cd/v2/util/localconfig"
)
// NewLogoutCommand returns a new instance of `argocd logout` command
diff --git a/cmd/argocd/commands/logout_test.go b/cmd/argocd/commands/logout_test.go
index 3ff28b2455..2a5c2da7b8 100644
--- a/cmd/argocd/commands/logout_test.go
+++ b/cmd/argocd/commands/logout_test.go
@@ -7,8 +7,8 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
- argocdclient "github.com/argoproj/argo-cd/v3/pkg/apiclient"
- "github.com/argoproj/argo-cd/v3/util/localconfig"
+ argocdclient "github.com/argoproj/argo-cd/v2/pkg/apiclient"
+ "github.com/argoproj/argo-cd/v2/util/localconfig"
)
func TestLogout(t *testing.T) {
diff --git a/cmd/argocd/commands/plugin.go b/cmd/argocd/commands/plugin.go
deleted file mode 100644
index 47e5a40e1a..0000000000
--- a/cmd/argocd/commands/plugin.go
+++ /dev/null
@@ -1,143 +0,0 @@
-package commands
-
-import (
- "errors"
- "fmt"
- "os"
- "os/exec"
- "path/filepath"
- "strings"
-
- "github.com/argoproj/argo-cd/v3/util/cli"
-
- log "github.com/sirupsen/logrus"
-)
-
-// DefaultPluginHandler implements the PluginHandler interface
-type DefaultPluginHandler struct {
- ValidPrefixes []string
- lookPath func(file string) (string, error)
- run func(cmd *exec.Cmd) error
-}
-
-// NewDefaultPluginHandler instantiates the DefaultPluginHandler
-func NewDefaultPluginHandler(validPrefixes []string) *DefaultPluginHandler {
- return &DefaultPluginHandler{
- ValidPrefixes: validPrefixes,
- lookPath: exec.LookPath,
- run: func(cmd *exec.Cmd) error {
- return cmd.Run()
- },
- }
-}
-
-// HandleCommandExecutionError processes the error returned from executing the command.
-// It handles both standard Argo CD commands and plugin commands. We don't require to return
-// error but we are doing it to cover various test scenarios.
-func (h *DefaultPluginHandler) HandleCommandExecutionError(err error, isArgocdCLI bool, args []string) error {
- // the log level needs to be setup manually here since the initConfig()
- // set by the cobra.OnInitialize() was never executed because cmd.Execute()
- // gave us a non-nil error.
- initConfig()
- cli.SetLogFormat("text")
- // If it's an unknown command error, attempt to handle it as a plugin.
- // Unfortunately, cobra doesn't handle this error, so we need to assume
- // that error consists of substring "unknown command".
- // https://github.com/spf13/cobra/pull/2167
- if isArgocdCLI && strings.Contains(err.Error(), "unknown command") {
- pluginPath, pluginErr := h.handlePluginCommand(args[1:])
- // IMP: If a plugin doesn't exist, the returned path will be empty along with nil error
- // This means the command is neither a normal Argo CD Command nor a plugin.
- if pluginErr != nil {
- // If plugin handling fails, report the plugin error and exit
- fmt.Printf("Error: %v\n", pluginErr)
- return pluginErr
- } else if pluginPath == "" {
- fmt.Printf("Error: %v\nRun 'argocd --help' for usage.\n", err)
- return err
- }
- } else {
- // If it's any other error (not an unknown command), report it directly and exit
- fmt.Printf("Error: %v\n", err)
- return err
- }
-
- return nil
-}
-
-// handlePluginCommand is responsible for finding and executing a plugin when a command isn't recognized as a built-in command
-func (h *DefaultPluginHandler) handlePluginCommand(cmdArgs []string) (string, error) {
- foundPluginPath := ""
- path, found := h.lookForPlugin(cmdArgs[0])
- if !found {
- return foundPluginPath, nil
- }
-
- foundPluginPath = path
-
- // Execute the plugin that is found
- if err := h.executePlugin(foundPluginPath, cmdArgs[1:], os.Environ()); err != nil {
- return foundPluginPath, err
- }
-
- return foundPluginPath, nil
-}
-
-// lookForPlugin looks for a plugin in the PATH that starts with argocd prefix
-func (h *DefaultPluginHandler) lookForPlugin(filename string) (string, bool) {
- for _, prefix := range h.ValidPrefixes {
- pluginName := fmt.Sprintf("%s-%s", prefix, filename)
- path, err := h.lookPath(pluginName)
- if err != nil {
- // error if a plugin is found in a relative path
- if errors.Is(err, exec.ErrDot) {
- log.Errorf("Plugin '%s' found in relative path: %v", pluginName, err)
- } else {
- log.Warnf("error looking for plugin '%s': %v", pluginName, err)
- }
- continue
- }
-
- if len(path) == 0 {
- return "", false
- }
-
- return path, true
- }
-
- return "", false
-}
-
-// executePlugin implements PluginHandler and executes a plugin found
-func (h *DefaultPluginHandler) executePlugin(executablePath string, cmdArgs, environment []string) error {
- cmd := h.command(executablePath, cmdArgs...)
- cmd.Stdout = os.Stdout
- cmd.Stderr = os.Stderr
- cmd.Stdin = os.Stdin
- cmd.Env = environment
-
- err := h.run(cmd)
- if err != nil {
- return err
- }
-
- return nil
-}
-
-// command creates a new command for all OSs
-func (h *DefaultPluginHandler) command(name string, arg ...string) *exec.Cmd {
- cmd := &exec.Cmd{
- Path: name,
- Args: append([]string{name}, arg...),
- }
- if filepath.Base(name) == name {
- lp, err := h.lookPath(name)
- if lp != "" && err != nil {
- // Update cmd.Path even if err is non-nil.
- // If err is ErrDot (especially on Windows), lp may include a resolved
- // extension (like .exe or .bat) that should be preserved.
- cmd.Path = lp
- }
- }
- return cmd
-}
diff --git a/cmd/argocd/commands/plugin_test.go b/cmd/argocd/commands/plugin_test.go
deleted file mode 100644
index 2f8ae88d08..0000000000
--- a/cmd/argocd/commands/plugin_test.go
+++ /dev/null
@@ -1,311 +0,0 @@
-package commands
-
-import (
- "bytes"
- "errors"
- "os"
- "os/exec"
- "path/filepath"
- "testing"
-
- argocdclient "github.com/argoproj/argo-cd/v3/pkg/apiclient"
-
- "github.com/stretchr/testify/assert"
- "github.com/stretchr/testify/require"
-)
-
-// setupPluginPath sets the PATH to the directory where plugins are stored for testing purpose
-func setupPluginPath(t *testing.T) {
- t.Helper()
- wd, err := os.Getwd()
- require.NoError(t, err)
- testdataPath := filepath.Join(wd, "testdata")
- t.Setenv("PATH", testdataPath)
-}
-
-// TestNormalCommandWithPlugin ensures that a standard ArgoCD command executes correctly
-// even when a plugin with the same name exists in the PATH
-func TestNormalCommandWithPlugin(t *testing.T) {
- setupPluginPath(t)
-
- _ = NewDefaultPluginHandler([]string{"argocd"})
- args := []string{"argocd", "version", "--short", "--client"}
- buf := new(bytes.Buffer)
- cmd := NewVersionCmd(&argocdclient.ClientOptions{}, nil)
- cmd.SetArgs(args[1:])
- cmd.SetOut(buf)
- cmd.SilenceErrors = true
- cmd.SilenceUsage = true
-
- err := cmd.Execute()
- require.NoError(t, err)
- output := buf.String()
- assert.Equal(t, "argocd: v99.99.99+unknown\n", output)
-}
-
-// TestPluginExecution verifies that a plugin found in the PATH executes successfully following the correct naming conventions
-func TestPluginExecution(t *testing.T) {
- setupPluginPath(t)
-
- pluginHandler := NewDefaultPluginHandler([]string{"argocd"})
- cmd := NewCommand()
- cmd.SilenceErrors = true
- cmd.SilenceUsage = true
-
- tests := []struct {
- name string
- args []string
- expectedPluginErr string
- }{
- {
- name: "'argocd-foo' binary exists in the PATH",
- args: []string{"argocd", "foo"},
- expectedPluginErr: "",
- },
- {
- name: "'argocd-demo_plugin' binary exists in the PATH",
- args: []string{"argocd", "demo_plugin"},
- expectedPluginErr: "",
- },
- {
- name: "'my-plugin' binary exists in the PATH",
- args: []string{"argocd", "my-plugin"},
- expectedPluginErr: "unknown command \"my-plugin\" for \"argocd\"",
- },
- {
- name: "'argocd_my-plugin' binary exists in the PATH",
- args: []string{"argocd", "my-plugin"},
- expectedPluginErr: "unknown command \"my-plugin\" for \"argocd\"",
- },
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- cmd.SetArgs(tt.args[1:])
-
- err := cmd.Execute()
- require.Error(t, err)
-
- // since the command is not a valid argocd command, check for plugin execution
- pluginErr := pluginHandler.HandleCommandExecutionError(err, true, tt.args)
- if tt.expectedPluginErr == "" {
- require.NoError(t, pluginErr)
- } else {
- require.EqualError(t, pluginErr, tt.expectedPluginErr)
- }
- })
- }
-}
-
-// TestNormalCommandError checks for an error when executing a normal ArgoCD command with invalid flags
-func TestNormalCommandError(t *testing.T) {
- setupPluginPath(t)
-
- pluginHandler := NewDefaultPluginHandler([]string{"argocd"})
- args := []string{"argocd", "version", "--non-existent-flag"}
- cmd := NewVersionCmd(&argocdclient.ClientOptions{}, nil)
- cmd.SetArgs(args[1:])
- cmd.SilenceErrors = true
- cmd.SilenceUsage = true
-
- err := cmd.Execute()
- require.Error(t, err)
-
- pluginErr := pluginHandler.HandleCommandExecutionError(err, true, args)
- assert.EqualError(t, pluginErr, "unknown flag: --non-existent-flag")
-}
-
-// TestUnknownCommandNoPlugin tests the scenario when the command is neither a normal ArgoCD command
-// nor exists as a plugin
-func TestUnknownCommandNoPlugin(t *testing.T) {
- pluginHandler := NewDefaultPluginHandler([]string{"argocd"})
- cmd := NewCommand()
- cmd.SilenceErrors = true
- cmd.SilenceUsage = true
- args := []string{"argocd", "non-existent"}
- cmd.SetArgs(args[1:])
-
- err := cmd.Execute()
- require.Error(t, err)
-
- pluginErr := pluginHandler.HandleCommandExecutionError(err, true, args)
- require.Error(t, pluginErr)
- assert.Equal(t, err, pluginErr)
-}
-
-// TestPluginNoExecutePermission verifies the behavior when a plugin doesn't have executable permissions
-func TestPluginNoExecutePermission(t *testing.T) {
- setupPluginPath(t)
-
- pluginHandler := NewDefaultPluginHandler([]string{"argocd"})
- cmd := NewCommand()
- cmd.SilenceErrors = true
- cmd.SilenceUsage = true
- args := []string{"argocd", "no-permission"}
- cmd.SetArgs(args[1:])
-
- err := cmd.Execute()
- require.Error(t, err)
-
- pluginErr := pluginHandler.HandleCommandExecutionError(err, true, args)
- require.Error(t, pluginErr)
- assert.EqualError(t, pluginErr, "unknown command \"no-permission\" for \"argocd\"")
-}
-
-// TestPluginExecutionError checks for errors that occur during plugin execution
-func TestPluginExecutionError(t *testing.T) {
- setupPluginPath(t)
-
- pluginHandler := NewDefaultPluginHandler([]string{"argocd"})
- cmd := NewCommand()
- cmd.SilenceErrors = true
- cmd.SilenceUsage = true
- args := []string{"argocd", "error"}
- cmd.SetArgs(args[1:])
-
- err := cmd.Execute()
- require.Error(t, err)
-
- pluginErr := pluginHandler.HandleCommandExecutionError(err, true, args)
- require.Error(t, pluginErr)
- assert.EqualError(t, pluginErr, "exit status 1")
-}
-
-// TestPluginInRelativePathIgnored ensures that plugins in a relative path, even if the path is included in PATH,
-// are ignored and not executed.
-func TestPluginInRelativePathIgnored(t *testing.T) {
- setupPluginPath(t)
-
- relativePath := "./relative-plugins"
- err := os.MkdirAll(relativePath, 0o755)
- require.NoError(t, err)
- defer os.RemoveAll(relativePath)
-
- relativePluginPath := filepath.Join(relativePath, "argocd-ignore-plugin")
- err = os.WriteFile(relativePluginPath, []byte("#!/bin/bash\necho 'This should not execute'\n"), 0o755)
- require.NoError(t, err)
-
- t.Setenv("PATH", os.Getenv("PATH")+string(os.PathListSeparator)+relativePath)
-
- pluginHandler := NewDefaultPluginHandler([]string{"argocd"})
- cmd := NewCommand()
- cmd.SilenceErrors = true
- cmd.SilenceUsage = true
- args := []string{"argocd", "ignore-plugin"}
- cmd.SetArgs(args[1:])
-
- err = cmd.Execute()
- require.Error(t, err)
-
- pluginErr := pluginHandler.HandleCommandExecutionError(err, true, args)
- require.Error(t, pluginErr)
- assert.EqualError(t, pluginErr, "unknown command \"ignore-plugin\" for \"argocd\"")
-}
-
-// TestPluginFlagParsing checks that the flags are parsed correctly by the plugin handler
-func TestPluginFlagParsing(t *testing.T) {
- setupPluginPath(t)
-
- pluginHandler := NewDefaultPluginHandler([]string{"argocd"})
-
- tests := []struct {
- name string
- args []string
- shouldFail bool
- expectedErrMsg string
- }{
- {
- name: "Valid flags",
- args: []string{"argocd", "test-plugin", "--flag1", "value1", "--flag2", "value2"},
- shouldFail: false,
- expectedErrMsg: "",
- },
- {
- name: "Unknown flag",
- args: []string{"argocd", "test-plugin", "--flag3", "invalid"},
- shouldFail: true,
- expectedErrMsg: "exit status 1",
- },
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- cmd := NewCommand()
- cmd.SilenceErrors = true
- cmd.SilenceUsage = true
-
- cmd.SetArgs(tt.args[1:])
-
- err := cmd.Execute()
- require.Error(t, err)
-
- pluginErr := pluginHandler.HandleCommandExecutionError(err, true, tt.args)
-
- if tt.shouldFail {
- require.Error(t, pluginErr)
- assert.Equal(t, tt.expectedErrMsg, pluginErr.Error(), "Unexpected error message")
- } else {
- require.NoError(t, pluginErr, "Expected no error for valid flags")
- }
- })
- }
-}
-
-// TestPluginStatusCode checks for a correct status code that a plugin binary would generate
-func TestPluginStatusCode(t *testing.T) {
- setupPluginPath(t)
-
- pluginHandler := NewDefaultPluginHandler([]string{"argocd"})
-
- tests := []struct {
- name string
- args []string
- wantStatus int
- throwErr bool
- }{
- {
- name: "plugin generates the successful exit code",
- args: []string{"argocd", "status-code-plugin", "--flag1", "value1"},
- wantStatus: 0,
- throwErr: false,
- },
- {
- name: "plugin generates an error status code",
- args: []string{"argocd", "status-code-plugin", "--flag3", "value3"},
- wantStatus: 1,
- throwErr: true,
- },
- {
- name: "plugin generates a status code for an invalid command",
- args: []string{"argocd", "status-code-plugin", "invalid"},
- wantStatus: 127,
- throwErr: true,
- },
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- cmd := NewCommand()
- cmd.SilenceErrors = true
- cmd.SilenceUsage = true
-
- cmd.SetArgs(tt.args[1:])
-
- err := cmd.Execute()
- require.Error(t, err)
-
- pluginErr := pluginHandler.HandleCommandExecutionError(err, true, tt.args)
- if !tt.throwErr {
- require.NoError(t, pluginErr)
- } else {
- require.Error(t, pluginErr)
- var exitErr *exec.ExitError
- if errors.As(pluginErr, &exitErr) {
- assert.Equal(t, tt.wantStatus, exitErr.ExitCode(), "unexpected exit code")
- } else {
- t.Fatalf("expected an exit error, got: %v", pluginErr)
- }
- }
- })
- }
-}
diff --git a/cmd/argocd/commands/project.go b/cmd/argocd/commands/project.go
index 3477d3eecb..b3dc9498d6 100644
--- a/cmd/argocd/commands/project.go
+++ b/cmd/argocd/commands/project.go
@@ -17,18 +17,18 @@ import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"sigs.k8s.io/yaml"
- "github.com/argoproj/argo-cd/v3/cmd/argocd/commands/headless"
- "github.com/argoproj/argo-cd/v3/cmd/argocd/commands/utils"
- cmdutil "github.com/argoproj/argo-cd/v3/cmd/util"
- argocdclient "github.com/argoproj/argo-cd/v3/pkg/apiclient"
- projectpkg "github.com/argoproj/argo-cd/v3/pkg/apiclient/project"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- "github.com/argoproj/argo-cd/v3/util/cli"
- "github.com/argoproj/argo-cd/v3/util/errors"
- "github.com/argoproj/argo-cd/v3/util/git"
- "github.com/argoproj/argo-cd/v3/util/gpg"
- utilio "github.com/argoproj/argo-cd/v3/util/io"
- "github.com/argoproj/argo-cd/v3/util/templates"
+ "github.com/argoproj/argo-cd/v2/cmd/argocd/commands/headless"
+ "github.com/argoproj/argo-cd/v2/cmd/argocd/commands/utils"
+ cmdutil "github.com/argoproj/argo-cd/v2/cmd/util"
+ argocdclient "github.com/argoproj/argo-cd/v2/pkg/apiclient"
+ projectpkg "github.com/argoproj/argo-cd/v2/pkg/apiclient/project"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/util/cli"
+ "github.com/argoproj/argo-cd/v2/util/errors"
+ "github.com/argoproj/argo-cd/v2/util/git"
+ "github.com/argoproj/argo-cd/v2/util/gpg"
+ argoio "github.com/argoproj/argo-cd/v2/util/io"
+ "github.com/argoproj/argo-cd/v2/util/templates"
)
type policyOpts struct {
@@ -122,7 +122,7 @@ func NewProjectCreateCommand(clientOpts *argocdclient.ClientOptions) *cobra.Comm
errors.CheckError(err)
conn, projIf := headless.NewClientOrDie(clientOpts, c).NewProjectClientOrDie()
- defer utilio.Close(conn)
+ defer argoio.Close(conn)
_, err = projIf.Create(ctx, &projectpkg.ProjectCreateRequest{Project: proj, Upsert: upsert})
errors.CheckError(err)
},
@@ -159,7 +159,7 @@ func NewProjectSetCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command
}
projName := args[0]
conn, projIf := headless.NewClientOrDie(clientOpts, c).NewProjectClientOrDie()
- defer utilio.Close(conn)
+ defer argoio.Close(conn)
proj, err := projIf.Get(ctx, &projectpkg.ProjectQuery{Name: projName})
errors.CheckError(err)
@@ -202,7 +202,7 @@ func NewProjectAddSignatureKeyCommand(clientOpts *argocdclient.ClientOptions) *c
}
conn, projIf := headless.NewClientOrDie(clientOpts, c).NewProjectClientOrDie()
- defer utilio.Close(conn)
+ defer argoio.Close(conn)
proj, err := projIf.Get(ctx, &projectpkg.ProjectQuery{Name: projName})
errors.CheckError(err)
@@ -240,7 +240,7 @@ func NewProjectRemoveSignatureKeyCommand(clientOpts *argocdclient.ClientOptions)
signatureKey := args[1]
conn, projIf := headless.NewClientOrDie(clientOpts, c).NewProjectClientOrDie()
- defer utilio.Close(conn)
+ defer argoio.Close(conn)
proj, err := projIf.Get(ctx, &projectpkg.ProjectQuery{Name: projName})
errors.CheckError(err)
@@ -254,10 +254,11 @@ 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)
},
}
@@ -296,7 +297,7 @@ func NewProjectAddDestinationCommand(clientOpts *argocdclient.ClientOptions) *co
namespace := args[2]
destination := buildApplicationDestination(args[1], namespace, nameInsteadServer)
conn, projIf := headless.NewClientOrDie(clientOpts, c).NewProjectClientOrDie()
- defer utilio.Close(conn)
+ defer argoio.Close(conn)
proj, err := projIf.Get(ctx, &projectpkg.ProjectQuery{Name: projName})
errors.CheckError(err)
@@ -337,7 +338,7 @@ func NewProjectRemoveDestinationCommand(clientOpts *argocdclient.ClientOptions)
server := args[1]
namespace := args[2]
conn, projIf := headless.NewClientOrDie(clientOpts, c).NewProjectClientOrDie()
- defer utilio.Close(conn)
+ defer argoio.Close(conn)
proj, err := projIf.Get(ctx, &projectpkg.ProjectQuery{Name: projName})
errors.CheckError(err)
@@ -351,10 +352,11 @@ 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)
},
}
@@ -385,7 +387,7 @@ func NewProjectAddOrphanedIgnoreCommand(clientOpts *argocdclient.ClientOptions)
group := args[1]
kind := args[2]
conn, projIf := headless.NewClientOrDie(clientOpts, c).NewProjectClientOrDie()
- defer utilio.Close(conn)
+ defer argoio.Close(conn)
proj, err := projIf.Get(ctx, &projectpkg.ProjectQuery{Name: projName})
errors.CheckError(err)
@@ -435,7 +437,7 @@ func NewProjectRemoveOrphanedIgnoreCommand(clientOpts *argocdclient.ClientOption
group := args[1]
kind := args[2]
conn, projIf := headless.NewClientOrDie(clientOpts, c).NewProjectClientOrDie()
- defer utilio.Close(conn)
+ defer argoio.Close(conn)
proj, err := projIf.Get(ctx, &projectpkg.ProjectQuery{Name: projName})
errors.CheckError(err)
@@ -454,10 +456,11 @@ 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")
@@ -483,13 +486,13 @@ func NewProjectAddSourceCommand(clientOpts *argocdclient.ClientOptions) *cobra.C
projName := args[0]
url := args[1]
conn, projIf := headless.NewClientOrDie(clientOpts, c).NewProjectClientOrDie()
- defer utilio.Close(conn)
+ defer argoio.Close(conn)
proj, err := projIf.Get(ctx, &projectpkg.ProjectQuery{Name: projName})
errors.CheckError(err)
for _, item := range proj.Spec.SourceRepos {
- if item == "*" {
+ if item == "*" && item == url {
fmt.Printf("Source repository '*' already allowed in project\n")
return
}
@@ -525,7 +528,7 @@ func NewProjectAddSourceNamespace(clientOpts *argocdclient.ClientOptions) *cobra
projName := args[0]
srcNamespace := args[1]
conn, projIf := headless.NewClientOrDie(clientOpts, c).NewProjectClientOrDie()
- defer utilio.Close(conn)
+ defer argoio.Close(conn)
proj, err := projIf.Get(ctx, &projectpkg.ProjectQuery{Name: projName})
errors.CheckError(err)
@@ -563,7 +566,7 @@ func NewProjectRemoveSourceNamespace(clientOpts *argocdclient.ClientOptions) *co
projName := args[0]
srcNamespace := args[1]
conn, projIf := headless.NewClientOrDie(clientOpts, c).NewProjectClientOrDie()
- defer utilio.Close(conn)
+ defer argoio.Close(conn)
proj, err := projIf.Get(ctx, &projectpkg.ProjectQuery{Name: projName})
errors.CheckError(err)
@@ -599,21 +602,22 @@ 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
- }
- index := -1
- for i, item := range *list {
- if item.Group == group && item.Kind == kind {
- index = i
- break
+ } 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
+ }
+ *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 {
@@ -639,7 +643,7 @@ func modifyResourceListCmd(cmdUse, cmdDesc, examples string, clientOpts *argocdc
}
projName, group, kind := args[0], args[1], args[2]
conn, projIf := headless.NewClientOrDie(clientOpts, c).NewProjectClientOrDie()
- defer utilio.Close(conn)
+ defer argoio.Close(conn)
proj, err := projIf.Get(ctx, &projectpkg.ProjectQuery{Name: projName})
errors.CheckError(err)
@@ -737,7 +741,7 @@ func NewProjectRemoveSourceCommand(clientOpts *argocdclient.ClientOptions) *cobr
projName := args[0]
url := args[1]
conn, projIf := headless.NewClientOrDie(clientOpts, c).NewProjectClientOrDie()
- defer utilio.Close(conn)
+ defer argoio.Close(conn)
proj, err := projIf.Get(ctx, &projectpkg.ProjectQuery{Name: projName})
errors.CheckError(err)
@@ -782,7 +786,7 @@ func NewProjectDeleteCommand(clientOpts *argocdclient.ClientOptions) *cobra.Comm
promptUtil := utils.NewPrompt(clientOpts.PromptsEnabled)
conn, projIf := headless.NewClientOrDie(clientOpts, c).NewProjectClientOrDie()
- defer utilio.Close(conn)
+ defer argoio.Close(conn)
for _, name := range args {
canDelete := promptUtil.Confirm(fmt.Sprintf("Are you sure you want to delete %s? [y/n]", name))
if canDelete {
@@ -827,11 +831,11 @@ func NewProjectListCommand(clientOpts *argocdclient.ClientOptions) *cobra.Comman
# List all available projects in yaml format
argocd proj list -o yaml
`),
- Run: func(c *cobra.Command, _ []string) {
+ Run: func(c *cobra.Command, args []string) {
ctx := c.Context()
conn, projIf := headless.NewClientOrDie(clientOpts, c).NewProjectClientOrDie()
- defer utilio.Close(conn)
+ defer argoio.Close(conn)
projects, err := projIf.List(ctx, &projectpkg.ProjectQuery{})
errors.CheckError(err)
switch output {
@@ -1023,7 +1027,7 @@ func NewProjectGetCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command
os.Exit(1)
}
projName := args[0]
- detailedProject := getProject(ctx, c, clientOpts, projName)
+ detailedProject := getProject(c, clientOpts, ctx, projName)
switch output {
case "yaml", "json":
@@ -1040,9 +1044,9 @@ func NewProjectGetCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command
return command
}
-func getProject(ctx context.Context, c *cobra.Command, clientOpts *argocdclient.ClientOptions, projName string) *projectpkg.DetailedProjectsResponse {
+func getProject(c *cobra.Command, clientOpts *argocdclient.ClientOptions, ctx context.Context, projName string) *projectpkg.DetailedProjectsResponse {
conn, projIf := headless.NewClientOrDie(clientOpts, c).NewProjectClientOrDie()
- defer utilio.Close(conn)
+ defer argoio.Close(conn)
detailedProject, err := projIf.GetDetailedProject(ctx, &projectpkg.ProjectQuery{Name: projName})
errors.CheckError(err)
return detailedProject
@@ -1065,7 +1069,7 @@ func NewProjectEditCommand(clientOpts *argocdclient.ClientOptions) *cobra.Comman
}
projName := args[0]
conn, projIf := headless.NewClientOrDie(clientOpts, c).NewProjectClientOrDie()
- defer utilio.Close(conn)
+ defer argoio.Close(conn)
proj, err := projIf.Get(ctx, &projectpkg.ProjectQuery{Name: projName})
errors.CheckError(err)
projData, err := json.Marshal(proj.Spec)
@@ -1073,7 +1077,7 @@ func NewProjectEditCommand(clientOpts *argocdclient.ClientOptions) *cobra.Comman
projData, err = yaml.JSONToYAML(projData)
errors.CheckError(err)
- cli.InteractiveEdit(projName+"-*-edit.yaml", projData, func(input []byte) error {
+ cli.InteractiveEdit(fmt.Sprintf("%s-*-edit.yaml", projName), projData, func(input []byte) error {
input, err = yaml.YAMLToJSON(input)
if err != nil {
return fmt.Errorf("error converting YAML to JSON: %w", err)
@@ -1110,11 +1114,12 @@ func NewProjectAddDestinationServiceAccountCommand(clientOpts *argocdclient.Clie
Namespace: namespace,
DefaultServiceAccount: fmt.Sprintf("%s:%s", serviceAccountNamespace, serviceAccount),
}
- }
- return v1alpha1.ApplicationDestinationServiceAccount{
- Server: destination,
- Namespace: namespace,
- DefaultServiceAccount: serviceAccount,
+ } else {
+ return v1alpha1.ApplicationDestinationServiceAccount{
+ Server: destination,
+ Namespace: namespace,
+ DefaultServiceAccount: serviceAccount,
+ }
}
}
@@ -1150,7 +1155,7 @@ func NewProjectAddDestinationServiceAccountCommand(clientOpts *argocdclient.Clie
destinationServiceAccount := buildApplicationDestinationServiceAccount(server, namespace, serviceAccount, serviceAccountNamespace)
conn, projIf := headless.NewClientOrDie(clientOpts, c).NewProjectClientOrDie()
- defer utilio.Close(conn)
+ defer argoio.Close(conn)
proj, err := projIf.Get(ctx, &projectpkg.ProjectQuery{Name: projName})
errors.CheckError(err)
@@ -1192,7 +1197,7 @@ func NewProjectRemoveDestinationServiceAccountCommand(clientOpts *argocdclient.C
namespace := args[2]
serviceAccount := args[3]
conn, projIf := headless.NewClientOrDie(clientOpts, c).NewProjectClientOrDie()
- defer utilio.Close(conn)
+ defer argoio.Close(conn)
proj, err := projIf.Get(ctx, &projectpkg.ProjectQuery{Name: projName})
errors.CheckError(err)
@@ -1205,11 +1210,12 @@ func NewProjectRemoveDestinationServiceAccountCommand(clientOpts *argocdclient.C
destServiceAccount.DefaultServiceAccount == serviceAccount
},
)
- if originalLength == len(proj.Spec.DestinationServiceAccounts) {
+ if originalLength != len(proj.Spec.DestinationServiceAccounts) {
+ _, err = projIf.Update(ctx, &projectpkg.ProjectUpdateRequest{Project: proj})
+ errors.CheckError(err)
+ } else {
log.Fatal("Specified destination service account does not exist in project")
}
- _, err = projIf.Update(ctx, &projectpkg.ProjectUpdateRequest{Project: proj})
- errors.CheckError(err)
},
}
diff --git a/cmd/argocd/commands/project_role.go b/cmd/argocd/commands/project_role.go
index f8715c3c38..a0da6793fa 100644
--- a/cmd/argocd/commands/project_role.go
+++ b/cmd/argocd/commands/project_role.go
@@ -7,20 +7,19 @@ import (
"text/tabwriter"
"time"
- timeutil "github.com/argoproj/pkg/v2/time"
- jwtgo "github.com/golang-jwt/jwt/v5"
+ timeutil "github.com/argoproj/pkg/time"
+ jwtgo "github.com/golang-jwt/jwt/v4"
"github.com/spf13/cobra"
- "github.com/argoproj/argo-cd/v3/cmd/argocd/commands/headless"
- "github.com/argoproj/argo-cd/v3/cmd/argocd/commands/utils"
- argocdclient "github.com/argoproj/argo-cd/v3/pkg/apiclient"
- projectpkg "github.com/argoproj/argo-cd/v3/pkg/apiclient/project"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- claimsutil "github.com/argoproj/argo-cd/v3/util/claims"
- "github.com/argoproj/argo-cd/v3/util/errors"
- utilio "github.com/argoproj/argo-cd/v3/util/io"
- "github.com/argoproj/argo-cd/v3/util/jwt"
- "github.com/argoproj/argo-cd/v3/util/templates"
+ "github.com/argoproj/argo-cd/v2/cmd/argocd/commands/headless"
+ "github.com/argoproj/argo-cd/v2/cmd/argocd/commands/utils"
+ argocdclient "github.com/argoproj/argo-cd/v2/pkg/apiclient"
+ projectpkg "github.com/argoproj/argo-cd/v2/pkg/apiclient/project"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/util/errors"
+ "github.com/argoproj/argo-cd/v2/util/io"
+ "github.com/argoproj/argo-cd/v2/util/jwt"
+ "github.com/argoproj/argo-cd/v2/util/templates"
)
const (
@@ -91,7 +90,7 @@ ID ISSUED-AT EXPIRES-AT
projName := args[0]
roleName := args[1]
conn, projIf := headless.NewClientOrDie(clientOpts, c).NewProjectClientOrDie()
- defer utilio.Close(conn)
+ defer io.Close(conn)
proj, err := projIf.Get(ctx, &projectpkg.ProjectQuery{Name: projName})
errors.CheckError(err)
@@ -150,7 +149,7 @@ ID ISSUED-AT EXPIRES-AT
projName := args[0]
roleName := args[1]
conn, projIf := headless.NewClientOrDie(clientOpts, c).NewProjectClientOrDie()
- defer utilio.Close(conn)
+ defer io.Close(conn)
proj, err := projIf.Get(ctx, &projectpkg.ProjectQuery{Name: projName})
errors.CheckError(err)
@@ -192,7 +191,7 @@ func NewProjectRoleCreateCommand(clientOpts *argocdclient.ClientOptions) *cobra.
command := &cobra.Command{
Use: "create PROJECT ROLE-NAME",
Short: "Create a project role",
- Example: templates.Examples(`
+ Example: templates.Examples(`
# Create a project role in the "my-project" project with the name "my-role".
argocd proj role create my-project my-role --description "My project role description"
`),
@@ -207,7 +206,7 @@ func NewProjectRoleCreateCommand(clientOpts *argocdclient.ClientOptions) *cobra.
projName := args[0]
roleName := args[1]
conn, projIf := headless.NewClientOrDie(clientOpts, c).NewProjectClientOrDie()
- defer utilio.Close(conn)
+ defer io.Close(conn)
proj, err := projIf.Get(ctx, &projectpkg.ProjectQuery{Name: projName})
errors.CheckError(err)
@@ -244,7 +243,7 @@ func NewProjectRoleDeleteCommand(clientOpts *argocdclient.ClientOptions) *cobra.
projName := args[0]
roleName := args[1]
conn, projIf := headless.NewClientOrDie(clientOpts, c).NewProjectClientOrDie()
- defer utilio.Close(conn)
+ defer io.Close(conn)
promptUtil := utils.NewPrompt(clientOpts.PromptsEnabled)
@@ -308,7 +307,7 @@ Create token succeeded for proj:test-project:test-role.
projName := args[0]
roleName := args[1]
conn, projIf := headless.NewClientOrDie(clientOpts, c).NewProjectClientOrDie()
- defer utilio.Close(conn)
+ defer io.Close(conn)
if expiresIn == "" {
expiresIn = "0s"
}
@@ -322,24 +321,18 @@ Create token succeeded for proj:test-project:test-role.
})
errors.CheckError(err)
- var claims jwtgo.MapClaims
- _, _, err = jwtgo.NewParser().ParseUnverified(tokenResponse.Token, &claims)
- if err != nil {
+ token, err := jwtgo.Parse(tokenResponse.Token, nil)
+ if token == nil {
err = fmt.Errorf("received malformed token %w", err)
errors.CheckError(err)
return
}
- argoClaims, err := claimsutil.MapClaimsToArgoClaims(claims)
- if err != nil {
- errors.CheckError(fmt.Errorf("invalid argo claims: %w", err))
- return
- }
-
+ claims := token.Claims.(jwtgo.MapClaims)
issuedAt, _ := jwt.IssuedAt(claims)
expiresAt := int64(jwt.Float64Field(claims, "exp"))
- id := argoClaims.ID
- subject := argoClaims.GetUserIdentifier()
+ id := jwt.StringField(claims, "jti")
+ subject := jwt.StringField(claims, "sub")
if !outputTokenOnly {
fmt.Printf("Create token succeeded for %s.\n", subject)
@@ -383,7 +376,7 @@ fa9d3517-c52d-434c-9bff-215b38508842 2023-10-08T11:08:18+01:00 Never
roleName := args[1]
conn, projIf := headless.NewClientOrDie(clientOpts, c).NewProjectClientOrDie()
- defer utilio.Close(conn)
+ defer io.Close(conn)
proj, err := projIf.Get(ctx, &projectpkg.ProjectQuery{Name: projName})
errors.CheckError(err)
@@ -466,7 +459,7 @@ $ argocd proj role delete-token test-project test-role 1696769937
promptUtil := utils.NewPrompt(clientOpts.PromptsEnabled)
conn, projIf := headless.NewClientOrDie(clientOpts, c).NewProjectClientOrDie()
- defer utilio.Close(conn)
+ defer io.Close(conn)
canDelete := promptUtil.Confirm(fmt.Sprintf("Are you sure you want to delete '%s' project token? [y/n]", tokenId))
if canDelete {
@@ -503,7 +496,7 @@ func NewProjectRoleListCommand(clientOpts *argocdclient.ClientOptions) *cobra.Co
command := &cobra.Command{
Use: "list PROJECT",
Short: "List all the roles in a project",
- Example: templates.Examples(`
+ Example: templates.Examples(`
# This command will list all the roles in argocd-project in a default table format.
argocd proj role list PROJECT
@@ -521,7 +514,7 @@ func NewProjectRoleListCommand(clientOpts *argocdclient.ClientOptions) *cobra.Co
}
projName := args[0]
conn, projIf := headless.NewClientOrDie(clientOpts, c).NewProjectClientOrDie()
- defer utilio.Close(conn)
+ defer io.Close(conn)
project, err := projIf.Get(ctx, &projectpkg.ProjectQuery{Name: projName})
errors.CheckError(err)
@@ -567,7 +560,7 @@ ID ISSUED-AT EXPIRES-AT
projName := args[0]
roleName := args[1]
conn, projIf := headless.NewClientOrDie(clientOpts, c).NewProjectClientOrDie()
- defer utilio.Close(conn)
+ defer io.Close(conn)
proj, err := projIf.Get(ctx, &projectpkg.ProjectQuery{Name: projName})
errors.CheckError(err)
@@ -611,7 +604,7 @@ func NewProjectRoleAddGroupCommand(clientOpts *argocdclient.ClientOptions) *cobr
}
projName, roleName, groupName := args[0], args[1], args[2]
conn, projIf := headless.NewClientOrDie(clientOpts, c).NewProjectClientOrDie()
- defer utilio.Close(conn)
+ defer io.Close(conn)
proj, err := projIf.Get(ctx, &projectpkg.ProjectQuery{Name: projName})
errors.CheckError(err)
updated, err := proj.AddGroupToRole(roleName, groupName)
@@ -642,7 +635,7 @@ func NewProjectRoleRemoveGroupCommand(clientOpts *argocdclient.ClientOptions) *c
}
projName, roleName, groupName := args[0], args[1], args[2]
conn, projIf := headless.NewClientOrDie(clientOpts, c).NewProjectClientOrDie()
- defer utilio.Close(conn)
+ defer io.Close(conn)
proj, err := projIf.Get(ctx, &projectpkg.ProjectQuery{Name: projName})
errors.CheckError(err)
updated, err := proj.RemoveGroupFromRole(roleName, groupName)
diff --git a/cmd/argocd/commands/projectwindows.go b/cmd/argocd/commands/projectwindows.go
index 239b9e2c85..589064b240 100644
--- a/cmd/argocd/commands/projectwindows.go
+++ b/cmd/argocd/commands/projectwindows.go
@@ -9,13 +9,13 @@ import (
"github.com/spf13/cobra"
- "github.com/argoproj/argo-cd/v3/cmd/argocd/commands/headless"
- "github.com/argoproj/argo-cd/v3/cmd/argocd/commands/utils"
- argocdclient "github.com/argoproj/argo-cd/v3/pkg/apiclient"
- projectpkg "github.com/argoproj/argo-cd/v3/pkg/apiclient/project"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- "github.com/argoproj/argo-cd/v3/util/errors"
- utilio "github.com/argoproj/argo-cd/v3/util/io"
+ "github.com/argoproj/argo-cd/v2/cmd/argocd/commands/headless"
+ "github.com/argoproj/argo-cd/v2/cmd/argocd/commands/utils"
+ argocdclient "github.com/argoproj/argo-cd/v2/pkg/apiclient"
+ projectpkg "github.com/argoproj/argo-cd/v2/pkg/apiclient/project"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/util/errors"
+ "github.com/argoproj/argo-cd/v2/util/io"
)
// NewProjectWindowsCommand returns a new instance of the `argocd proj windows` command
@@ -30,7 +30,7 @@ argocd proj windows add my-project \
--duration 3600 \
--prune
-#Delete a sync window from a project
+#Delete a sync window from a project
argocd proj windows delete
#List project sync windows
@@ -56,8 +56,8 @@ func NewProjectWindowsDisableManualSyncCommand(clientOpts *argocdclient.ClientOp
Short: "Disable manual sync for a sync window",
Long: "Disable manual sync for a sync window. Requires ID which can be found by running \"argocd proj windows list PROJECT\"",
Example: `
-#Disable manual sync for a sync window for the Project
-argocd proj windows disable-manual-sync PROJECT ID
+#Disable manual sync for a sync window for the Project
+argocd proj windows disable-manual-sync PROJECT ID
#Disabling manual sync for a windows set on the default project with Id 0
argocd proj windows disable-manual-sync default 0`,
@@ -74,7 +74,7 @@ argocd proj windows disable-manual-sync default 0`,
errors.CheckError(err)
conn, projIf := headless.NewClientOrDie(clientOpts, c).NewProjectClientOrDie()
- defer utilio.Close(conn)
+ defer io.Close(conn)
proj, err := projIf.Get(ctx, &projectpkg.ProjectQuery{Name: projName})
errors.CheckError(err)
@@ -100,7 +100,7 @@ func NewProjectWindowsEnableManualSyncCommand(clientOpts *argocdclient.ClientOpt
Long: "Enable manual sync for a sync window. Requires ID which can be found by running \"argocd proj windows list PROJECT\"",
Example: `
#Enabling manual sync for a general case
-argocd proj windows enable-manual-sync PROJECT ID
+argocd proj windows enable-manual-sync PROJECT ID
#Enabling manual sync for a windows set on the default project with Id 2
argocd proj windows enable-manual-sync default 2
@@ -120,7 +120,7 @@ argocd proj windows enable-manual-sync my-app-project --message "Manual sync ini
errors.CheckError(err)
conn, projIf := headless.NewClientOrDie(clientOpts, c).NewProjectClientOrDie()
- defer utilio.Close(conn)
+ defer io.Close(conn)
proj, err := projIf.Get(ctx, &projectpkg.ProjectQuery{Name: projName})
errors.CheckError(err)
@@ -149,8 +149,6 @@ func NewProjectWindowsAddWindowCommand(clientOpts *argocdclient.ClientOptions) *
clusters []string
manualSync bool
timeZone string
- andOperator bool
- description string
)
command := &cobra.Command{
Use: "add PROJECT",
@@ -161,8 +159,7 @@ argocd proj windows add PROJECT \
--kind allow \
--schedule "0 22 * * *" \
--duration 1h \
- --applications "*" \
- --description "Ticket 123"
+ --applications "*"
#Add a deny sync window with the ability to manually sync.
argocd proj windows add PROJECT \
@@ -172,8 +169,7 @@ argocd proj windows add PROJECT \
--applications "prod-\\*,website" \
--namespaces "default,\\*-prod" \
--clusters "prod,staging" \
- --manual-sync \
- --description "Ticket 123"
+ --manual-sync
`,
Run: func(c *cobra.Command, args []string) {
ctx := c.Context()
@@ -184,12 +180,12 @@ argocd proj windows add PROJECT \
}
projName := args[0]
conn, projIf := headless.NewClientOrDie(clientOpts, c).NewProjectClientOrDie()
- defer utilio.Close(conn)
+ defer io.Close(conn)
proj, err := projIf.Get(ctx, &projectpkg.ProjectQuery{Name: projName})
errors.CheckError(err)
- err = proj.Spec.AddWindow(kind, schedule, duration, applications, namespaces, clusters, manualSync, timeZone, andOperator, description)
+ err = proj.Spec.AddWindow(kind, schedule, duration, applications, namespaces, clusters, manualSync, timeZone)
errors.CheckError(err)
_, err = projIf.Update(ctx, &projectpkg.ProjectUpdateRequest{Project: proj})
@@ -204,8 +200,6 @@ argocd proj windows add PROJECT \
command.Flags().StringSliceVar(&clusters, "clusters", []string{}, "Clusters that the schedule will be applied to. Comma separated, wildcards supported (e.g. --clusters prod,staging)")
command.Flags().BoolVar(&manualSync, "manual-sync", false, "Allow manual syncs for both deny and allow windows")
command.Flags().StringVar(&timeZone, "time-zone", "UTC", "Time zone of the sync window")
- command.Flags().BoolVar(&andOperator, "use-and-operator", false, "Use AND operator for matching applications, namespaces and clusters instead of the default OR operator")
- command.Flags().StringVar(&description, "description", "", `Sync window description`)
return command
}
@@ -216,7 +210,7 @@ func NewProjectWindowsDeleteCommand(clientOpts *argocdclient.ClientOptions) *cob
Use: "delete PROJECT ID",
Short: "Delete a sync window from a project. Requires ID which can be found by running \"argocd proj windows list PROJECT\"",
Example: `
-#Delete a sync window from a project (default) with ID 0
+#Delete a sync window from a project (default) with ID 0
argocd proj windows delete default 0
#Delete a sync window from a project (new-project) with ID 1
@@ -234,7 +228,7 @@ argocd proj windows delete new-project 1`,
errors.CheckError(err)
conn, projIf := headless.NewClientOrDie(clientOpts, c).NewProjectClientOrDie()
- defer utilio.Close(conn)
+ defer io.Close(conn)
proj, err := projIf.Get(ctx, &projectpkg.ProjectQuery{Name: projName})
errors.CheckError(err)
@@ -264,7 +258,6 @@ func NewProjectWindowsUpdateCommand(clientOpts *argocdclient.ClientOptions) *cob
namespaces []string
clusters []string
timeZone string
- description string
)
command := &cobra.Command{
Use: "update PROJECT ID",
@@ -287,14 +280,14 @@ argocd proj windows update PROJECT ID \
errors.CheckError(err)
conn, projIf := headless.NewClientOrDie(clientOpts, c).NewProjectClientOrDie()
- defer utilio.Close(conn)
+ defer io.Close(conn)
proj, err := projIf.Get(ctx, &projectpkg.ProjectQuery{Name: projName})
errors.CheckError(err)
for i, window := range proj.Spec.SyncWindows {
if id == i {
- err := window.Update(schedule, duration, applications, namespaces, clusters, timeZone, description)
+ err := window.Update(schedule, duration, applications, namespaces, clusters, timeZone)
if err != nil {
errors.CheckError(err)
}
@@ -311,7 +304,6 @@ argocd proj windows update PROJECT ID \
command.Flags().StringSliceVar(&namespaces, "namespaces", []string{}, "Namespaces that the schedule will be applied to. Comma separated, wildcards supported (e.g. --namespaces default,\\*-prod)")
command.Flags().StringSliceVar(&clusters, "clusters", []string{}, "Clusters that the schedule will be applied to. Comma separated, wildcards supported (e.g. --clusters prod,staging)")
command.Flags().StringVar(&timeZone, "time-zone", "UTC", "Time zone of the sync window. (e.g. --time-zone \"America/New_York\")")
- command.Flags().StringVar(&description, "description", "", "Sync window description")
return command
}
@@ -339,7 +331,7 @@ argocd proj windows list test-project`,
}
projName := args[0]
conn, projIf := headless.NewClientOrDie(clientOpts, c).NewProjectClientOrDie()
- defer utilio.Close(conn)
+ defer io.Close(conn)
proj, err := projIf.Get(ctx, &projectpkg.ProjectQuery{Name: projName})
errors.CheckError(err)
@@ -362,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 := []any{"ID", "STATUS", "KIND", "SCHEDULE", "DURATION", "APPLICATIONS", "NAMESPACES", "CLUSTERS", "MANUALSYNC", "TIMEZONE"}
+ headers := []interface{}{"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 := []any{
+ vals := []interface{}{
strconv.Itoa(i),
formatBoolOutput(isActive),
window.Kind,
@@ -377,9 +369,8 @@ func printSyncWindows(proj *v1alpha1.AppProject) {
formatListOutput(window.Applications),
formatListOutput(window.Namespaces),
formatListOutput(window.Clusters),
- formatBoolEnabledOutput(window.ManualSync),
+ formatManualOutput(window.ManualSync),
window.TimeZone,
- formatBoolEnabledOutput(window.UseAndOperator),
}
fmt.Fprintf(w, fmtStr, vals...)
}
@@ -407,7 +398,7 @@ func formatBoolOutput(active bool) string {
return o
}
-func formatBoolEnabledOutput(active bool) string {
+func formatManualOutput(active bool) string {
var o string
if active {
o = "Enabled"
diff --git a/cmd/argocd/commands/relogin.go b/cmd/argocd/commands/relogin.go
index 5eec14a581..effb0239c0 100644
--- a/cmd/argocd/commands/relogin.go
+++ b/cmd/argocd/commands/relogin.go
@@ -8,13 +8,13 @@ import (
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
- "github.com/argoproj/argo-cd/v3/cmd/argocd/commands/headless"
- argocdclient "github.com/argoproj/argo-cd/v3/pkg/apiclient"
- settingspkg "github.com/argoproj/argo-cd/v3/pkg/apiclient/settings"
- "github.com/argoproj/argo-cd/v3/util/errors"
- utilio "github.com/argoproj/argo-cd/v3/util/io"
- "github.com/argoproj/argo-cd/v3/util/localconfig"
- "github.com/argoproj/argo-cd/v3/util/session"
+ "github.com/argoproj/argo-cd/v2/cmd/argocd/commands/headless"
+ argocdclient "github.com/argoproj/argo-cd/v2/pkg/apiclient"
+ settingspkg "github.com/argoproj/argo-cd/v2/pkg/apiclient/settings"
+ "github.com/argoproj/argo-cd/v2/util/errors"
+ argoio "github.com/argoproj/argo-cd/v2/util/io"
+ "github.com/argoproj/argo-cd/v2/util/localconfig"
+ "github.com/argoproj/argo-cd/v2/util/session"
)
// NewReloginCommand returns a new instance of `argocd relogin` command
@@ -65,7 +65,7 @@ func NewReloginCommand(globalClientOpts *argocdclient.ClientOptions) *cobra.Comm
} else {
fmt.Println("Reinitiating SSO login")
setConn, setIf := acdClient.NewSettingsClientOrDie()
- defer utilio.Close(setConn)
+ defer argoio.Close(setConn)
httpClient, err := acdClient.HTTPClient()
errors.CheckError(err)
ctx = oidc.ClientContext(ctx, httpClient)
diff --git a/cmd/argocd/commands/relogin_test.go b/cmd/argocd/commands/relogin_test.go
index e8a2c554dc..9b6e1e7d83 100644
--- a/cmd/argocd/commands/relogin_test.go
+++ b/cmd/argocd/commands/relogin_test.go
@@ -7,7 +7,7 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
- argocdclient "github.com/argoproj/argo-cd/v3/pkg/apiclient"
+ argocdclient "github.com/argoproj/argo-cd/v2/pkg/apiclient"
)
func TestNewReloginCommand(t *testing.T) {
@@ -24,7 +24,7 @@ func TestNewReloginCommand(t *testing.T) {
// Assert command flags
passwordFlag := cmd.Flags().Lookup("password")
assert.NotNil(t, passwordFlag, "Expected flag --password to be defined")
- assert.Empty(t, passwordFlag.Value.String(), "Unexpected default value for --password flag")
+ assert.Equal(t, "", passwordFlag.Value.String(), "Unexpected default value for --password flag")
ssoPortFlag := cmd.Flags().Lookup("sso-port")
port, err := strconv.Atoi(ssoPortFlag.Value.String())
@@ -55,7 +55,7 @@ func TestNewReloginCommandWithGlobalClientOptions(t *testing.T) {
// Assert command flags
passwordFlag := cmd.Flags().Lookup("password")
assert.NotNil(t, passwordFlag, "Expected flag --password to be defined")
- assert.Empty(t, passwordFlag.Value.String(), "Unexpected default value for --password flag")
+ assert.Equal(t, "", passwordFlag.Value.String(), "Unexpected default value for --password flag")
ssoPortFlag := cmd.Flags().Lookup("sso-port")
port, err := strconv.Atoi(ssoPortFlag.Value.String())
diff --git a/cmd/argocd/commands/repo.go b/cmd/argocd/commands/repo.go
index 3619cc1b62..3aba1b2e65 100644
--- a/cmd/argocd/commands/repo.go
+++ b/cmd/argocd/commands/repo.go
@@ -1,7 +1,6 @@
package commands
import (
- stderrors "errors"
"fmt"
"os"
"strconv"
@@ -10,16 +9,16 @@ import (
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
- "github.com/argoproj/argo-cd/v3/cmd/argocd/commands/headless"
- "github.com/argoproj/argo-cd/v3/cmd/argocd/commands/utils"
- cmdutil "github.com/argoproj/argo-cd/v3/cmd/util"
- argocdclient "github.com/argoproj/argo-cd/v3/pkg/apiclient"
- repositorypkg "github.com/argoproj/argo-cd/v3/pkg/apiclient/repository"
- appsv1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- "github.com/argoproj/argo-cd/v3/util/cli"
- "github.com/argoproj/argo-cd/v3/util/errors"
- "github.com/argoproj/argo-cd/v3/util/git"
- utilio "github.com/argoproj/argo-cd/v3/util/io"
+ "github.com/argoproj/argo-cd/v2/cmd/argocd/commands/headless"
+ "github.com/argoproj/argo-cd/v2/cmd/argocd/commands/utils"
+ cmdutil "github.com/argoproj/argo-cd/v2/cmd/util"
+ argocdclient "github.com/argoproj/argo-cd/v2/pkg/apiclient"
+ repositorypkg "github.com/argoproj/argo-cd/v2/pkg/apiclient/repository"
+ appsv1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/util/cli"
+ "github.com/argoproj/argo-cd/v2/util/errors"
+ "github.com/argoproj/argo-cd/v2/util/git"
+ "github.com/argoproj/argo-cd/v2/util/io"
)
// NewRepoCommand returns a new instance of an `argocd repo` command
@@ -119,14 +118,15 @@ func NewRepoAddCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command {
}
repoOpts.Repo.SSHPrivateKey = string(keyData)
} else {
- errors.Fatal(errors.ErrorGeneric, "--ssh-private-key-path is only supported for SSH repositories.")
+ err := fmt.Errorf("--ssh-private-key-path is only supported for SSH repositories.")
+ errors.CheckError(err)
}
}
// tls-client-cert-path and tls-client-cert-key-key-path must always be
// specified together
if (repoOpts.TlsClientCertPath != "" && repoOpts.TlsClientCertKeyPath == "") || (repoOpts.TlsClientCertPath == "" && repoOpts.TlsClientCertKeyPath != "") {
- err := stderrors.New("--tls-client-cert-path and --tls-client-cert-key-path must be specified together")
+ err := fmt.Errorf("--tls-client-cert-path and --tls-client-cert-key-path must be specified together")
errors.CheckError(err)
}
@@ -140,7 +140,7 @@ func NewRepoAddCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command {
repoOpts.Repo.TLSClientCertData = string(tlsCertData)
repoOpts.Repo.TLSClientCertKey = string(tlsCertKey)
} else {
- err := stderrors.New("--tls-client-cert-path is only supported for HTTPS repositories")
+ err := fmt.Errorf("--tls-client-cert-path is only supported for HTTPS repositories")
errors.CheckError(err)
}
}
@@ -152,7 +152,7 @@ func NewRepoAddCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command {
errors.CheckError(err)
repoOpts.Repo.GithubAppPrivateKey = string(githubAppPrivateKey)
} else {
- err := stderrors.New("--github-app-private-key-path is only supported for HTTPS repositories")
+ err := fmt.Errorf("--github-app-private-key-path is only supported for HTTPS repositories")
errors.CheckError(err)
}
}
@@ -163,7 +163,7 @@ func NewRepoAddCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command {
errors.CheckError(err)
repoOpts.Repo.GCPServiceAccountKey = string(gcpServiceAccountKey)
} else {
- err := stderrors.New("--gcp-service-account-key-path is only supported for HTTPS repositories")
+ err := fmt.Errorf("--gcp-service-account-key-path is only supported for HTTPS repositories")
errors.CheckError(err)
}
}
@@ -181,14 +181,13 @@ func NewRepoAddCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command {
repoOpts.Repo.Proxy = repoOpts.Proxy
repoOpts.Repo.NoProxy = repoOpts.NoProxy
repoOpts.Repo.ForceHttpBasicAuth = repoOpts.ForceHttpBasicAuth
- repoOpts.Repo.UseAzureWorkloadIdentity = repoOpts.UseAzureWorkloadIdentity
if repoOpts.Repo.Type == "helm" && repoOpts.Repo.Name == "" {
- errors.Fatal(errors.ErrorGeneric, "Must specify --name for repos of type 'helm'")
+ errors.CheckError(fmt.Errorf("Must specify --name for repos of type 'helm'"))
}
conn, repoIf := headless.NewClientOrDie(clientOpts, c).NewRepoClientOrDie()
- defer utilio.Close(conn)
+ defer io.Close(conn)
// If the user set a username, but didn't supply password via --password,
// then we prompt for it
@@ -196,13 +195,6 @@ func NewRepoAddCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command {
repoOpts.Repo.Password = cli.PromptPassword(repoOpts.Repo.Password)
}
- err := cmdutil.ValidateBearerTokenAndPasswordCombo(repoOpts.Repo.BearerToken, repoOpts.Repo.Password)
- errors.CheckError(err)
- err = cmdutil.ValidateBearerTokenForGitOnly(repoOpts.Repo.BearerToken, repoOpts.Repo.Type)
- errors.CheckError(err)
- err = cmdutil.ValidateBearerTokenForHTTPSRepoOnly(repoOpts.Repo.BearerToken, git.IsHTTPSURL(repoOpts.Repo.Repo))
- errors.CheckError(err)
-
// We let the server check access to the repository before adding it. If
// it is a private repo, but we cannot access with with the credentials
// that were supplied, we bail out.
@@ -216,7 +208,6 @@ func NewRepoAddCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command {
Name: repoOpts.Repo.Name,
Username: repoOpts.Repo.Username,
Password: repoOpts.Repo.Password,
- BearerToken: repoOpts.Repo.BearerToken,
SshPrivateKey: repoOpts.Repo.SSHPrivateKey,
TlsClientCertData: repoOpts.Repo.TLSClientCertData,
TlsClientCertKey: repoOpts.Repo.TLSClientCertKey,
@@ -230,9 +221,8 @@ func NewRepoAddCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command {
Project: repoOpts.Repo.Project,
GcpServiceAccountKey: repoOpts.Repo.GCPServiceAccountKey,
ForceHttpBasicAuth: repoOpts.Repo.ForceHttpBasicAuth,
- UseAzureWorkloadIdentity: repoOpts.Repo.UseAzureWorkloadIdentity,
}
- _, err = repoIf.ValidateAccess(ctx, &repoAccessReq)
+ _, err := repoIf.ValidateAccess(ctx, &repoAccessReq)
errors.CheckError(err)
repoCreateReq := repositorypkg.RepoCreateRequest{
@@ -264,7 +254,7 @@ func NewRepoRemoveCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command
os.Exit(1)
}
conn, repoIf := headless.NewClientOrDie(clientOpts, c).NewRepoClientOrDie()
- defer utilio.Close(conn)
+ defer io.Close(conn)
promptUtil := utils.NewPrompt(clientOpts.PromptsEnabled)
for _, repoURL := range args {
@@ -316,18 +306,18 @@ func NewRepoListCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command {
command := &cobra.Command{
Use: "list",
Short: "List configured repositories",
- Run: func(c *cobra.Command, _ []string) {
+ Run: func(c *cobra.Command, args []string) {
ctx := c.Context()
conn, repoIf := headless.NewClientOrDie(clientOpts, c).NewRepoClientOrDie()
- defer utilio.Close(conn)
+ defer io.Close(conn)
forceRefresh := false
switch refresh {
case "":
case "hard":
forceRefresh = true
default:
- err := stderrors.New("--refresh must be one of: 'hard'")
+ err := fmt.Errorf("--refresh must be one of: 'hard'")
errors.CheckError(err)
}
repos, err := repoIf.ListRepositories(ctx, &repositorypkg.RepoQuery{ForceRefresh: forceRefresh})
@@ -372,14 +362,14 @@ func NewRepoGetCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command {
// Repository URL
repoURL := args[0]
conn, repoIf := headless.NewClientOrDie(clientOpts, c).NewRepoClientOrDie()
- defer utilio.Close(conn)
+ defer io.Close(conn)
forceRefresh := false
switch refresh {
case "":
case "hard":
forceRefresh = true
default:
- err := stderrors.New("--refresh must be one of: 'hard'")
+ err := fmt.Errorf("--refresh must be one of: 'hard'")
errors.CheckError(err)
}
repo, err := repoIf.Get(ctx, &repositorypkg.RepoQuery{Repo: repoURL, ForceRefresh: forceRefresh, AppProject: project})
diff --git a/cmd/argocd/commands/repocreds.go b/cmd/argocd/commands/repocreds.go
index 213a7c7d8d..215895d5fc 100644
--- a/cmd/argocd/commands/repocreds.go
+++ b/cmd/argocd/commands/repocreds.go
@@ -1,7 +1,6 @@
package commands
import (
- stderrors "errors"
"fmt"
"os"
"text/tabwriter"
@@ -9,25 +8,24 @@ import (
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
- "github.com/argoproj/argo-cd/v3/cmd/argocd/commands/headless"
- "github.com/argoproj/argo-cd/v3/cmd/argocd/commands/utils"
- cmdutil "github.com/argoproj/argo-cd/v3/cmd/util"
- "github.com/argoproj/argo-cd/v3/common"
- argocdclient "github.com/argoproj/argo-cd/v3/pkg/apiclient"
- repocredspkg "github.com/argoproj/argo-cd/v3/pkg/apiclient/repocreds"
- appsv1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- "github.com/argoproj/argo-cd/v3/util/cli"
- "github.com/argoproj/argo-cd/v3/util/errors"
- "github.com/argoproj/argo-cd/v3/util/git"
- utilio "github.com/argoproj/argo-cd/v3/util/io"
- "github.com/argoproj/argo-cd/v3/util/templates"
+ "github.com/argoproj/argo-cd/v2/cmd/argocd/commands/headless"
+ "github.com/argoproj/argo-cd/v2/cmd/argocd/commands/utils"
+ "github.com/argoproj/argo-cd/v2/common"
+ argocdclient "github.com/argoproj/argo-cd/v2/pkg/apiclient"
+ repocredspkg "github.com/argoproj/argo-cd/v2/pkg/apiclient/repocreds"
+ appsv1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/util/cli"
+ "github.com/argoproj/argo-cd/v2/util/errors"
+ "github.com/argoproj/argo-cd/v2/util/git"
+ "github.com/argoproj/argo-cd/v2/util/io"
+ "github.com/argoproj/argo-cd/v2/util/templates"
)
// NewRepoCredsCommand returns a new instance of an `argocd repocreds` command
func NewRepoCredsCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command {
command := &cobra.Command{
Use: "repocreds",
- Short: "Manage credential templates for repositories",
+ Short: "Manage repository connection parameters",
Example: templates.Examples(`
# Add credentials with user/pass authentication to use for all repositories under the specified URL
argocd repocreds add URL --username USERNAME --password PASSWORD
@@ -66,9 +64,6 @@ func NewRepoCredsAddCommand(clientOpts *argocdclient.ClientOptions) *cobra.Comma
repocredsAddExamples := ` # Add credentials with user/pass authentication to use for all repositories under https://git.example.com/repos
argocd repocreds add https://git.example.com/repos/ --username git --password secret
- # Add credentials with bearer token authentication to use for all BitBucket Data Center repositories under https://bitbucket.example.com/scm
- argocd repocreds add https://bitbucket.example.com/scm/ --bearer-token secret-token
-
# Add credentials with SSH private key authentication to use for all repositories under ssh://git@git.example.com/repos
argocd repocreds add ssh://git@git.example.com/repos/ --ssh-private-key-path ~/.ssh/id_rsa
@@ -109,14 +104,16 @@ func NewRepoCredsAddCommand(clientOpts *argocdclient.ClientOptions) *cobra.Comma
}
repo.SSHPrivateKey = string(keyData)
} else {
- errors.Fatal(errors.ErrorGeneric, "--ssh-private-key-path is only supported for SSH repositories.")
+ err := fmt.Errorf("--ssh-private-key-path is only supported for SSH repositories.")
+ errors.CheckError(err)
}
}
// tls-client-cert-path and tls-client-cert-key-key-path must always be
// specified together
if (tlsClientCertPath != "" && tlsClientCertKeyPath == "") || (tlsClientCertPath == "" && tlsClientCertKeyPath != "") {
- errors.Fatal(errors.ErrorGeneric, "--tls-client-cert-path and --tls-client-cert-key-path must be specified together")
+ err := fmt.Errorf("--tls-client-cert-path and --tls-client-cert-key-path must be specified together")
+ errors.CheckError(err)
}
// Specifying tls-client-cert-path is only valid for HTTPS repositories
@@ -129,7 +126,7 @@ func NewRepoCredsAddCommand(clientOpts *argocdclient.ClientOptions) *cobra.Comma
repo.TLSClientCertData = string(tlsCertData)
repo.TLSClientCertKey = string(tlsCertKey)
} else {
- err := stderrors.New("--tls-client-cert-path is only supported for HTTPS repositories")
+ err := fmt.Errorf("--tls-client-cert-path is only supported for HTTPS repositories")
errors.CheckError(err)
}
}
@@ -141,7 +138,7 @@ func NewRepoCredsAddCommand(clientOpts *argocdclient.ClientOptions) *cobra.Comma
errors.CheckError(err)
repo.GithubAppPrivateKey = string(githubAppPrivateKey)
} else {
- err := stderrors.New("--github-app-private-key-path is only supported for HTTPS repositories")
+ err := fmt.Errorf("--github-app-private-key-path is only supported for HTTPS repositories")
errors.CheckError(err)
}
}
@@ -153,13 +150,13 @@ func NewRepoCredsAddCommand(clientOpts *argocdclient.ClientOptions) *cobra.Comma
errors.CheckError(err)
repo.GCPServiceAccountKey = string(gcpServiceAccountKey)
} else {
- err := stderrors.New("--gcp-service-account-key-path is only supported for HTTPS repositories")
+ err := fmt.Errorf("--gcp-service-account-key-path is only supported for HTTPS repositories")
errors.CheckError(err)
}
}
conn, repoIf := headless.NewClientOrDie(clientOpts, c).NewRepoCredsClientOrDie()
- defer utilio.Close(conn)
+ defer io.Close(conn)
// If the user set a username, but didn't supply password via --password,
// then we prompt for it
@@ -167,13 +164,6 @@ func NewRepoCredsAddCommand(clientOpts *argocdclient.ClientOptions) *cobra.Comma
repo.Password = cli.PromptPassword(repo.Password)
}
- err := cmdutil.ValidateBearerTokenAndPasswordCombo(repo.BearerToken, repo.Password)
- errors.CheckError(err)
- err = cmdutil.ValidateBearerTokenForGitOnly(repo.BearerToken, repo.Type)
- errors.CheckError(err)
- err = cmdutil.ValidateBearerTokenForHTTPSRepoOnly(repo.BearerToken, git.IsHTTPSURL(repo.URL))
- errors.CheckError(err)
-
repoCreateReq := repocredspkg.RepoCredsCreateRequest{
Creds: &repo,
Upsert: upsert,
@@ -186,7 +176,6 @@ func NewRepoCredsAddCommand(clientOpts *argocdclient.ClientOptions) *cobra.Comma
}
command.Flags().StringVar(&repo.Username, "username", "", "username to the repository")
command.Flags().StringVar(&repo.Password, "password", "", "password to the repository")
- command.Flags().StringVar(&repo.BearerToken, "bearer-token", "", "bearer token to the Git repository")
command.Flags().StringVar(&sshPrivateKeyPath, "ssh-private-key-path", "", "path to the private ssh key (e.g. ~/.ssh/id_rsa)")
command.Flags().StringVar(&tlsClientCertPath, "tls-client-cert-path", "", "path to the TLS client cert (must be PEM format)")
command.Flags().StringVar(&tlsClientCertKeyPath, "tls-client-cert-key-path", "", "path to the TLS client cert's key path (must be PEM format)")
@@ -199,7 +188,6 @@ func NewRepoCredsAddCommand(clientOpts *argocdclient.ClientOptions) *cobra.Comma
command.Flags().StringVar(&repo.Type, "type", common.DefaultRepoType, "type of the repository, \"git\" or \"helm\"")
command.Flags().StringVar(&gcpServiceAccountKeyPath, "gcp-service-account-key-path", "", "service account key for the Google Cloud Platform")
command.Flags().BoolVar(&repo.ForceHttpBasicAuth, "force-http-basic-auth", false, "whether to force basic auth when connecting via HTTP")
- command.Flags().BoolVar(&repo.UseAzureWorkloadIdentity, "use-azure-workload-identity", false, "whether to use azure workload identity for authentication")
command.Flags().StringVar(&repo.Proxy, "proxy-url", "", "If provided, this URL will be used to connect via proxy")
return command
}
@@ -221,7 +209,7 @@ func NewRepoCredsRemoveCommand(clientOpts *argocdclient.ClientOptions) *cobra.Co
os.Exit(1)
}
conn, repoIf := headless.NewClientOrDie(clientOpts, c).NewRepoCredsClientOrDie()
- defer utilio.Close(conn)
+ defer io.Close(conn)
promptUtil := utils.NewPrompt(clientOpts.PromptsEnabled)
@@ -279,11 +267,11 @@ func NewRepoCredsListCommand(clientOpts *argocdclient.ClientOptions) *cobra.Comm
# List all repo urls in url format
argocd repocreds list -o url
`),
- Run: func(c *cobra.Command, _ []string) {
+ Run: func(c *cobra.Command, args []string) {
ctx := c.Context()
conn, repoIf := headless.NewClientOrDie(clientOpts, c).NewRepoCredsClientOrDie()
- defer utilio.Close(conn)
+ defer io.Close(conn)
repos, err := repoIf.ListRepositoryCredentials(ctx, &repocredspkg.RepoCredsQuery{})
errors.CheckError(err)
switch output {
diff --git a/cmd/argocd/commands/root.go b/cmd/argocd/commands/root.go
index ba8f0d5840..7323c444e4 100644
--- a/cmd/argocd/commands/root.go
+++ b/cmd/argocd/commands/root.go
@@ -3,21 +3,20 @@ package commands
import (
"fmt"
- "github.com/argoproj/argo-cd/v3/util/cache"
-
"github.com/spf13/cobra"
"k8s.io/client-go/tools/clientcmd"
- "github.com/argoproj/argo-cd/v3/cmd/argocd/commands/admin"
- "github.com/argoproj/argo-cd/v3/cmd/argocd/commands/initialize"
- cmdutil "github.com/argoproj/argo-cd/v3/cmd/util"
- "github.com/argoproj/argo-cd/v3/common"
- argocdclient "github.com/argoproj/argo-cd/v3/pkg/apiclient"
- "github.com/argoproj/argo-cd/v3/util/cli"
- "github.com/argoproj/argo-cd/v3/util/config"
- "github.com/argoproj/argo-cd/v3/util/env"
- "github.com/argoproj/argo-cd/v3/util/errors"
- "github.com/argoproj/argo-cd/v3/util/localconfig"
+ "github.com/argoproj/argo-cd/v2/cmd/argocd/commands/admin"
+ "github.com/argoproj/argo-cd/v2/cmd/argocd/commands/initialize"
+ cmdutil "github.com/argoproj/argo-cd/v2/cmd/util"
+ "github.com/argoproj/argo-cd/v2/common"
+ argocdclient "github.com/argoproj/argo-cd/v2/pkg/apiclient"
+ "github.com/argoproj/argo-cd/v2/util/cache"
+ "github.com/argoproj/argo-cd/v2/util/cli"
+ "github.com/argoproj/argo-cd/v2/util/config"
+ "github.com/argoproj/argo-cd/v2/util/env"
+ "github.com/argoproj/argo-cd/v2/util/errors"
+ "github.com/argoproj/argo-cd/v2/util/localconfig"
)
func init() {
@@ -67,7 +66,7 @@ func NewCommand() *cobra.Command {
defaultLocalConfigPath, err := localconfig.DefaultLocalConfigPath()
errors.CheckError(err)
command.PersistentFlags().StringVar(&clientOpts.ConfigPath, "config", config.GetFlag("config", defaultLocalConfigPath), "Path to Argo CD config")
- command.PersistentFlags().StringVar(&clientOpts.ServerAddr, "server", config.GetFlag("server", env.StringFromEnv(common.EnvServer, "")), "Argo CD server address")
+ command.PersistentFlags().StringVar(&clientOpts.ServerAddr, "server", config.GetFlag("server", ""), "Argo CD server address")
command.PersistentFlags().BoolVar(&clientOpts.PlainText, "plaintext", config.GetBoolFlag("plaintext"), "Disable TLS")
command.PersistentFlags().BoolVar(&clientOpts.Insecure, "insecure", config.GetBoolFlag("insecure"), "Skip server certificate and domain verification")
command.PersistentFlags().StringVar(&clientOpts.CertFile, "server-crt", config.GetFlag("server-crt", ""), "Server certificate file")
@@ -76,7 +75,7 @@ func NewCommand() *cobra.Command {
command.PersistentFlags().StringVar(&clientOpts.AuthToken, "auth-token", config.GetFlag("auth-token", env.StringFromEnv(common.EnvAuthToken, "")), fmt.Sprintf("Authentication token; set this or the %s environment variable", common.EnvAuthToken))
command.PersistentFlags().BoolVar(&clientOpts.GRPCWeb, "grpc-web", config.GetBoolFlag("grpc-web"), "Enables gRPC-web protocol. Useful if Argo CD server is behind proxy which does not support HTTP2.")
command.PersistentFlags().StringVar(&clientOpts.GRPCWebRootPath, "grpc-web-root-path", config.GetFlag("grpc-web-root-path", ""), "Enables gRPC-web protocol. Useful if Argo CD server is behind proxy which does not support HTTP2. Set web root.")
- command.PersistentFlags().StringVar(&cmdutil.LogFormat, "logformat", config.GetFlag("logformat", "json"), "Set the logging format. One of: json|text")
+ command.PersistentFlags().StringVar(&cmdutil.LogFormat, "logformat", config.GetFlag("logformat", "text"), "Set the logging format. One of: text|json")
command.PersistentFlags().StringVar(&cmdutil.LogLevel, "loglevel", config.GetFlag("loglevel", "info"), "Set the logging level. One of: debug|info|warn|error")
command.PersistentFlags().StringSliceVarP(&clientOpts.Headers, "header", "H", config.GetStringSliceFlag("header", []string{}), "Sets additional header to all requests made by Argo CD CLI. (Can be repeated multiple times to add multiple headers, also supports comma separated headers)")
command.PersistentFlags().BoolVar(&clientOpts.PortForward, "port-forward", config.GetBoolFlag("port-forward"), "Connect to a random argocd-server port using port forwarding")
diff --git a/cmd/argocd/commands/testdata/argocd-demo_plugin b/cmd/argocd/commands/testdata/argocd-demo_plugin
deleted file mode 100755
index 5c3ef35c5e..0000000000
--- a/cmd/argocd/commands/testdata/argocd-demo_plugin
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/bin/bash
-
-if [[ "$1" == "version" ]]
-then
- echo "1.0.0"
- exit 0
-fi
-
-if [[ "$1" == "config" ]]
-then
- echo "$KUBECONFIG"
- exit 0
-fi
-
-echo "I am a plugin named argocd-demo_plugin"
diff --git a/cmd/argocd/commands/testdata/argocd-error b/cmd/argocd/commands/testdata/argocd-error
deleted file mode 100755
index 365c3b851e..0000000000
--- a/cmd/argocd/commands/testdata/argocd-error
+++ /dev/null
@@ -1,17 +0,0 @@
-#!/bin/bash
-
-if [[ "$1" == "version" ]]
-then
- echo "1.0.0"
- exit 0
-fi
-
-if [[ "$1" == "config" ]]
-then
- echo "$KUBECONFIG"
- exit 0
-fi
-
-# Default behavior: simulate an error
-echo "Error: I am a plugin named argocd-error, and I encountered an error." >&2
-exit 1
diff --git a/cmd/argocd/commands/testdata/argocd-foo b/cmd/argocd/commands/testdata/argocd-foo
deleted file mode 100755
index 8a01221de4..0000000000
--- a/cmd/argocd/commands/testdata/argocd-foo
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/bin/bash
-
-if [[ "$1" == "version" ]]
-then
- echo "1.0.0"
- exit 0
-fi
-
-if [[ "$1" == "config" ]]
-then
- echo "$KUBECONFIG"
- exit 0
-fi
-
-echo "I am a plugin named argocd-foo"
diff --git a/cmd/argocd/commands/testdata/argocd-no-permission b/cmd/argocd/commands/testdata/argocd-no-permission
deleted file mode 100644
index 11332ad234..0000000000
--- a/cmd/argocd/commands/testdata/argocd-no-permission
+++ /dev/null
@@ -1,3 +0,0 @@
-#!/bin/bash
-
-echo "I can't be executed since I don't have executable permissions"
diff --git a/cmd/argocd/commands/testdata/argocd-status-code-plugin b/cmd/argocd/commands/testdata/argocd-status-code-plugin
deleted file mode 100755
index 3aaa1fabc4..0000000000
--- a/cmd/argocd/commands/testdata/argocd-status-code-plugin
+++ /dev/null
@@ -1,16 +0,0 @@
-#!/bin/bash
-
-case "$1" in
- "--flag1")
- echo "Flag1 detected: $2"
- exit 0
- ;;
- "--flag3")
- echo "Unknown argument: --flag3" >&2
- exit 1
- ;;
- *)
- echo "Plugin not found or invalid command" >&2
- exit 127
- ;;
-esac
diff --git a/cmd/argocd/commands/testdata/argocd-test-plugin b/cmd/argocd/commands/testdata/argocd-test-plugin
deleted file mode 100755
index 377d83c0ba..0000000000
--- a/cmd/argocd/commands/testdata/argocd-test-plugin
+++ /dev/null
@@ -1,16 +0,0 @@
-#!/bin/bash
-
-# Ensure we receive the expected flags and values
-while [[ "$#" -gt 0 ]]; do
- case $1 in
- --flag1) FLAG1="$2"; shift ;;
- --flag2) FLAG2="$2"; shift ;;
- --help) echo "Usage: argocd test-plugin --flag1 value1 --flag2 value2"; exit 0 ;;
- *) echo "Unknown argument: $1"; exit 1 ;;
- esac
- shift
-done
-
-# Output the parsed flag values
-echo "Flag1: ${FLAG1}"
-echo "Flag2: ${FLAG2}"
diff --git a/cmd/argocd/commands/testdata/argocd-version b/cmd/argocd/commands/testdata/argocd-version
deleted file mode 100755
index 9639838cf8..0000000000
--- a/cmd/argocd/commands/testdata/argocd-version
+++ /dev/null
@@ -1,4 +0,0 @@
-#!/bin/bash
-
-echo "Fetching the version of Argo CD..."
-argocd version --short --client
diff --git a/cmd/argocd/commands/testdata/argocd_my-plugin b/cmd/argocd/commands/testdata/argocd_my-plugin
deleted file mode 100755
index e63e98e780..0000000000
--- a/cmd/argocd/commands/testdata/argocd_my-plugin
+++ /dev/null
@@ -1,7 +0,0 @@
-#!/bin/sh
-
-echo "Hello from argocd_my-plugin"
-
-if [ "$#" -gt 0 ]; then
- echo "Arguments received: $@"
-fi
diff --git a/cmd/argocd/commands/testdata/my-plugin b/cmd/argocd/commands/testdata/my-plugin
deleted file mode 100755
index 42265877be..0000000000
--- a/cmd/argocd/commands/testdata/my-plugin
+++ /dev/null
@@ -1,7 +0,0 @@
-#!/bin/sh
-
-echo "Hello from my-plugin"
-
-if [ "$#" -gt 0 ]; then
- echo "Arguments received: $@"
-fi
diff --git a/cmd/argocd/commands/tree.go b/cmd/argocd/commands/tree.go
index ae87b82770..904b2e7d68 100644
--- a/cmd/argocd/commands/tree.go
+++ b/cmd/argocd/commands/tree.go
@@ -9,7 +9,7 @@ import (
"github.com/argoproj/gitops-engine/pkg/health"
"k8s.io/apimachinery/pkg/util/duration"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
)
const (
@@ -36,7 +36,7 @@ func treeViewAppGet(prefix string, uidToNodeMap map[string]v1alpha1.ResourceNode
_, _ = fmt.Fprintf(w, "%s%s\t%s\t%s\t%s\n", printPrefix(prefix), parent.Kind+"/"+parent.Name, "", healthStatus, "")
}
chs := parentToChildMap[parent.UID]
- for i, childUID := range chs {
+ for i, childUid := range chs {
var p string
switch i {
case len(chs) - 1:
@@ -44,7 +44,7 @@ func treeViewAppGet(prefix string, uidToNodeMap map[string]v1alpha1.ResourceNode
default:
p = prefix + firstElemPrefix
}
- treeViewAppGet(p, uidToNodeMap, parentToChildMap, uidToNodeMap[childUID], mapNodeNameToResourceState, w)
+ treeViewAppGet(p, uidToNodeMap, parentToChildMap, uidToNodeMap[childUid], mapNodeNameToResourceState, w)
}
}
diff --git a/cmd/argocd/commands/tree_test.go b/cmd/argocd/commands/tree_test.go
index 1dc7f47a91..c0d2129fed 100644
--- a/cmd/argocd/commands/tree_test.go
+++ b/cmd/argocd/commands/tree_test.go
@@ -8,7 +8,7 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
)
func TestTreeViewAppGet(t *testing.T) {
diff --git a/cmd/argocd/commands/utils/prompt.go b/cmd/argocd/commands/utils/prompt.go
index f3193cf4ac..4cda58aef5 100644
--- a/cmd/argocd/commands/utils/prompt.go
+++ b/cmd/argocd/commands/utils/prompt.go
@@ -1,7 +1,7 @@
package utils
import (
- "github.com/argoproj/argo-cd/v3/util/cli"
+ "github.com/argoproj/argo-cd/v2/util/cli"
)
type Prompt struct {
diff --git a/cmd/argocd/commands/version.go b/cmd/argocd/commands/version.go
index 47766d0240..8c69c4195c 100644
--- a/cmd/argocd/commands/version.go
+++ b/cmd/argocd/commands/version.go
@@ -8,12 +8,12 @@ import (
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
- "github.com/argoproj/argo-cd/v3/cmd/argocd/commands/headless"
- "github.com/argoproj/argo-cd/v3/common"
- argocdclient "github.com/argoproj/argo-cd/v3/pkg/apiclient"
- "github.com/argoproj/argo-cd/v3/pkg/apiclient/version"
- "github.com/argoproj/argo-cd/v3/util/errors"
- utilio "github.com/argoproj/argo-cd/v3/util/io"
+ "github.com/argoproj/argo-cd/v2/cmd/argocd/commands/headless"
+ "github.com/argoproj/argo-cd/v2/common"
+ argocdclient "github.com/argoproj/argo-cd/v2/pkg/apiclient"
+ "github.com/argoproj/argo-cd/v2/pkg/apiclient/version"
+ "github.com/argoproj/argo-cd/v2/util/errors"
+ argoio "github.com/argoproj/argo-cd/v2/util/io"
)
// NewVersionCmd returns a new `version` command to be used as a sub-command to root
@@ -39,13 +39,13 @@ 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, _ []string) {
+ Run: func(cmd *cobra.Command, args []string) {
ctx := cmd.Context()
cv := common.GetVersion()
switch output {
case "yaml", "json":
- v := make(map[string]any)
+ v := make(map[string]interface{})
if short {
v["client"] = map[string]string{cliName: cv.Version}
@@ -94,7 +94,7 @@ func NewVersionCmd(clientOpts *argocdclient.ClientOptions, serverVersion *versio
func getServerVersion(ctx context.Context, options *argocdclient.ClientOptions, c *cobra.Command) *version.VersionMessage {
conn, versionIf := headless.NewClientOrDie(options, c).NewVersionClientOrDie()
- defer utilio.Close(conn)
+ defer argoio.Close(conn)
v, err := versionIf.Version(ctx, &empty.Empty{})
errors.CheckError(err)
diff --git a/cmd/argocd/commands/version_test.go b/cmd/argocd/commands/version_test.go
index 890f187ade..fb85a491ec 100644
--- a/cmd/argocd/commands/version_test.go
+++ b/cmd/argocd/commands/version_test.go
@@ -7,8 +7,8 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
- argocdclient "github.com/argoproj/argo-cd/v3/pkg/apiclient"
- "github.com/argoproj/argo-cd/v3/pkg/apiclient/version"
+ argocdclient "github.com/argoproj/argo-cd/v2/pkg/apiclient"
+ "github.com/argoproj/argo-cd/v2/pkg/apiclient/version"
)
func TestShortVersionClient(t *testing.T) {
diff --git a/cmd/main.go b/cmd/main.go
index fb3efd9547..92eb27049c 100644
--- a/cmd/main.go
+++ b/cmd/main.go
@@ -1,38 +1,30 @@
package main
import (
- "errors"
"os"
- "os/exec"
"path/filepath"
- "github.com/spf13/cobra"
- "k8s.io/klog/v2"
+ "github.com/argoproj/argo-cd/v2/cmd/util"
- appcontroller "github.com/argoproj/argo-cd/v3/cmd/argocd-application-controller/commands"
- applicationset "github.com/argoproj/argo-cd/v3/cmd/argocd-applicationset-controller/commands"
- cmpserver "github.com/argoproj/argo-cd/v3/cmd/argocd-cmp-server/commands"
- commitserver "github.com/argoproj/argo-cd/v3/cmd/argocd-commit-server/commands"
- dex "github.com/argoproj/argo-cd/v3/cmd/argocd-dex/commands"
- gitaskpass "github.com/argoproj/argo-cd/v3/cmd/argocd-git-ask-pass/commands"
- k8sauth "github.com/argoproj/argo-cd/v3/cmd/argocd-k8s-auth/commands"
- notification "github.com/argoproj/argo-cd/v3/cmd/argocd-notification/commands"
- reposerver "github.com/argoproj/argo-cd/v3/cmd/argocd-repo-server/commands"
- apiserver "github.com/argoproj/argo-cd/v3/cmd/argocd-server/commands"
- cli "github.com/argoproj/argo-cd/v3/cmd/argocd/commands"
- "github.com/argoproj/argo-cd/v3/cmd/util"
- "github.com/argoproj/argo-cd/v3/util/log"
+ "github.com/spf13/cobra"
+
+ appcontroller "github.com/argoproj/argo-cd/v2/cmd/argocd-application-controller/commands"
+ applicationset "github.com/argoproj/argo-cd/v2/cmd/argocd-applicationset-controller/commands"
+ cmpserver "github.com/argoproj/argo-cd/v2/cmd/argocd-cmp-server/commands"
+ commitserver "github.com/argoproj/argo-cd/v2/cmd/argocd-commit-server/commands"
+ dex "github.com/argoproj/argo-cd/v2/cmd/argocd-dex/commands"
+ gitaskpass "github.com/argoproj/argo-cd/v2/cmd/argocd-git-ask-pass/commands"
+ k8sauth "github.com/argoproj/argo-cd/v2/cmd/argocd-k8s-auth/commands"
+ notification "github.com/argoproj/argo-cd/v2/cmd/argocd-notification/commands"
+ reposerver "github.com/argoproj/argo-cd/v2/cmd/argocd-repo-server/commands"
+ apiserver "github.com/argoproj/argo-cd/v2/cmd/argocd-server/commands"
+ cli "github.com/argoproj/argo-cd/v2/cmd/argocd/commands"
)
const (
binaryNameEnv = "ARGOCD_BINARY_NAME"
)
-func init() {
- // Make sure klog uses the configured log level and format.
- klog.SetLogger(log.NewLogrusLogger(log.NewWithCurrentConfig()))
-}
-
func main() {
var command *cobra.Command
@@ -41,12 +33,11 @@ func main() {
binaryName = val
}
- isArgocdCLI := false
-
+ isCLI := false
switch binaryName {
case "argocd", "argocd-linux-amd64", "argocd-darwin-amd64", "argocd-windows-amd64.exe":
command = cli.NewCommand()
- isArgocdCLI = true
+ isCLI = true
case "argocd-server":
command = apiserver.NewCommand()
case "argocd-application-controller":
@@ -55,7 +46,7 @@ func main() {
command = reposerver.NewCommand()
case "argocd-cmp-server":
command = cmpserver.NewCommand()
- isArgocdCLI = true
+ isCLI = true
case "argocd-commit-server":
command = commitserver.NewCommand()
case "argocd-dex":
@@ -64,41 +55,19 @@ func main() {
command = notification.NewCommand()
case "argocd-git-ask-pass":
command = gitaskpass.NewCommand()
- isArgocdCLI = true
+ isCLI = true
case "argocd-applicationset-controller":
command = applicationset.NewCommand()
case "argocd-k8s-auth":
command = k8sauth.NewCommand()
- isArgocdCLI = true
+ isCLI = true
default:
command = cli.NewCommand()
- isArgocdCLI = true
+ isCLI = true
}
- util.SetAutoMaxProcs(isArgocdCLI)
+ util.SetAutoMaxProcs(isCLI)
- if isArgocdCLI {
- // silence errors and usages since we'll be printing them manually.
- // This is because if we execute a plugin, the initial
- // errors and usage are always going to get printed that we don't want.
- command.SilenceErrors = true
- command.SilenceUsage = true
- }
-
- err := command.Execute()
- // if the err is non-nil, try to look for various scenarios
- // such as if the error is from the execution of a normal argocd command,
- // unknown command error or any other.
- if err != nil {
- pluginHandler := cli.NewDefaultPluginHandler([]string{"argocd"})
- pluginErr := pluginHandler.HandleCommandExecutionError(err, isArgocdCLI, os.Args)
- if pluginErr != nil {
- var exitErr *exec.ExitError
- if errors.As(pluginErr, &exitErr) {
- // Return the actual plugin exit code
- os.Exit(exitErr.ExitCode())
- }
- // Fallback to exit code 1 if the error isn't an exec.ExitError
- os.Exit(1)
- }
+ if err := command.Execute(); err != nil {
+ os.Exit(1)
}
}
diff --git a/cmd/util/app.go b/cmd/util/app.go
index 7f3ba56615..e66c03f4e9 100644
--- a/cmd/util/app.go
+++ b/cmd/util/app.go
@@ -2,7 +2,6 @@ package util
import (
"bufio"
- stderrors "errors"
"fmt"
"io"
"net/url"
@@ -19,15 +18,15 @@ import (
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+ v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/utils/ptr"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application"
- argoappv1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- "github.com/argoproj/argo-cd/v3/util/argo"
- "github.com/argoproj/argo-cd/v3/util/config"
- "github.com/argoproj/argo-cd/v3/util/errors"
- "github.com/argoproj/argo-cd/v3/util/text/label"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application"
+ argoappv1 "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/config"
+ "github.com/argoproj/argo-cd/v2/util/errors"
+ "github.com/argoproj/argo-cd/v2/util/text/label"
)
type AppOptions struct {
@@ -55,7 +54,7 @@ type AppOptions struct {
helmSkipTests bool
helmNamespace string
helmKubeVersion string
- helmApiVersions []string //nolint:revive //FIXME(var-naming)
+ helmApiVersions []string
project string
syncPolicy string
syncOptions []string
@@ -77,13 +76,11 @@ type AppOptions struct {
kustomizeCommonLabels []string
kustomizeCommonAnnotations []string
kustomizeLabelWithoutSelector bool
- kustomizeLabelIncludeTemplates bool
kustomizeForceCommonLabels bool
kustomizeForceCommonAnnotations bool
kustomizeNamespace string
kustomizeKubeVersion string
- kustomizeApiVersions []string //nolint:revive //FIXME(var-naming)
- ignoreMissingComponents bool
+ kustomizeApiVersions []string
pluginEnvs []string
Validate bool
directoryExclude string
@@ -165,13 +162,11 @@ func AddAppFlags(command *cobra.Command, opts *AppOptions) {
command.Flags().StringArrayVar(&opts.jsonnetLibs, "jsonnet-libs", []string{}, "Additional jsonnet libs (prefixed by repoRoot)")
command.Flags().StringArrayVar(&opts.kustomizeImages, "kustomize-image", []string{}, "Kustomize images (e.g. --kustomize-image node:8.15.0 --kustomize-image mysql=mariadb,alpine@sha256:24a0c4b4a4c0eb97a1aabb8e29f18e917d05abfe1b7a7c07857230879ce7d3d)")
command.Flags().StringArrayVar(&opts.kustomizeReplicas, "kustomize-replica", []string{}, "Kustomize replicas (e.g. --kustomize-replica my-development=2 --kustomize-replica my-statefulset=4)")
- command.Flags().BoolVar(&opts.ignoreMissingComponents, "ignore-missing-components", false, "Ignore locally missing component directories when setting Kustomize components")
command.Flags().StringArrayVar(&opts.pluginEnvs, "plugin-env", []string{}, "Additional plugin envs")
command.Flags().BoolVar(&opts.Validate, "validate", true, "Validation of repo and cluster")
command.Flags().StringArrayVar(&opts.kustomizeCommonLabels, "kustomize-common-label", []string{}, "Set common labels in Kustomize")
command.Flags().StringArrayVar(&opts.kustomizeCommonAnnotations, "kustomize-common-annotation", []string{}, "Set common labels in Kustomize")
- command.Flags().BoolVar(&opts.kustomizeLabelWithoutSelector, "kustomize-label-without-selector", false, "Do not apply common label to selectors. Also do not apply label to templates unless --kustomize-label-include-templates is set")
- command.Flags().BoolVar(&opts.kustomizeLabelIncludeTemplates, "kustomize-label-include-templates", false, "Apply common label to resource templates")
+ command.Flags().BoolVar(&opts.kustomizeLabelWithoutSelector, "kustomize-label-without-selector", false, "Do not apply common label to selectors or templates")
command.Flags().BoolVar(&opts.kustomizeForceCommonLabels, "kustomize-force-common-label", false, "Force common labels in Kustomize")
command.Flags().BoolVar(&opts.kustomizeForceCommonAnnotations, "kustomize-force-common-annotation", false, "Force common annotations in Kustomize")
command.Flags().StringVar(&opts.kustomizeNamespace, "kustomize-namespace", "", "Kustomize namespace")
@@ -203,12 +198,11 @@ func SetAppSpecOptions(flags *pflag.FlagSet, spec *argoappv1.ApplicationSpec, ap
}
source, visited = ConstructSource(source, *appOpts, flags)
if spec.HasMultipleSources() {
- switch {
- case sourcePosition == 0:
+ if sourcePosition == 0 {
spec.Sources[sourcePosition] = *source
- case sourcePosition > 0:
+ } else if sourcePosition > 0 {
spec.Sources[sourcePosition-1] = *source
- default:
+ } else {
spec.Sources = append(spec.Sources, *source)
}
} else {
@@ -264,8 +258,7 @@ func SetAppSpecOptions(flags *pflag.FlagSet, spec *argoappv1.ApplicationSpec, ap
spec.SyncPolicy = nil
}
case "sync-retry-limit":
- switch {
- case appOpts.retryLimit > 0:
+ if appOpts.retryLimit > 0 {
if spec.SyncPolicy == nil {
spec.SyncPolicy = &argoappv1.SyncPolicy{}
}
@@ -277,31 +270,31 @@ func SetAppSpecOptions(flags *pflag.FlagSet, spec *argoappv1.ApplicationSpec, ap
Factor: ptr.To(appOpts.retryBackoffFactor),
},
}
- case appOpts.retryLimit == 0:
+ } else if appOpts.retryLimit == 0 {
if spec.SyncPolicy.IsZero() {
spec.SyncPolicy = nil
} else {
spec.SyncPolicy.Retry = nil
}
- default:
+ } else {
log.Fatalf("Invalid sync-retry-limit [%d]", appOpts.retryLimit)
}
}
})
if flags.Changed("auto-prune") {
- if spec.SyncPolicy == nil || !spec.SyncPolicy.IsAutomatedSyncEnabled() {
+ if spec.SyncPolicy == nil || spec.SyncPolicy.Automated == nil {
log.Fatal("Cannot set --auto-prune: application not configured with automatic sync")
}
spec.SyncPolicy.Automated.Prune = appOpts.autoPrune
}
if flags.Changed("self-heal") {
- if spec.SyncPolicy == nil || !spec.SyncPolicy.IsAutomatedSyncEnabled() {
+ if spec.SyncPolicy == nil || spec.SyncPolicy.Automated == nil {
log.Fatal("Cannot set --self-heal: application not configured with automatic sync")
}
spec.SyncPolicy.Automated.SelfHeal = appOpts.selfHeal
}
if flags.Changed("allow-empty") {
- if spec.SyncPolicy == nil || !spec.SyncPolicy.IsAutomatedSyncEnabled() {
+ if spec.SyncPolicy == nil || spec.SyncPolicy.Automated == nil {
log.Fatal("Cannot set --allow-empty: application not configured with automatic sync")
}
spec.SyncPolicy.Automated.AllowEmpty = appOpts.allowEmpty
@@ -311,21 +304,19 @@ func SetAppSpecOptions(flags *pflag.FlagSet, spec *argoappv1.ApplicationSpec, ap
}
type kustomizeOpts struct {
- namePrefix string
- nameSuffix string
- images []string
- replicas []string
- version string
- commonLabels map[string]string
- commonAnnotations map[string]string
- labelWithoutSelector bool
- labelIncludeTemplates bool
- forceCommonLabels bool
- forceCommonAnnotations bool
- namespace string
- kubeVersion string
- apiVersions []string
- ignoreMissingComponents bool
+ namePrefix string
+ nameSuffix string
+ images []string
+ replicas []string
+ version string
+ commonLabels map[string]string
+ commonAnnotations map[string]string
+ labelWithoutSelector bool
+ forceCommonLabels bool
+ forceCommonAnnotations bool
+ namespace string
+ kubeVersion string
+ apiVersions []string
}
func setKustomizeOpt(src *argoappv1.ApplicationSource, opts kustomizeOpts) {
@@ -359,18 +350,12 @@ func setKustomizeOpt(src *argoappv1.ApplicationSource, opts kustomizeOpts) {
if opts.labelWithoutSelector {
src.Kustomize.LabelWithoutSelector = opts.labelWithoutSelector
}
- if opts.labelIncludeTemplates {
- src.Kustomize.LabelIncludeTemplates = opts.labelIncludeTemplates
- }
if opts.forceCommonLabels {
src.Kustomize.ForceCommonLabels = opts.forceCommonLabels
}
if opts.forceCommonAnnotations {
src.Kustomize.ForceCommonAnnotations = opts.forceCommonAnnotations
}
- if opts.ignoreMissingComponents {
- src.Kustomize.IgnoreMissingComponents = opts.ignoreMissingComponents
- }
for _, image := range opts.images {
src.Kustomize.MergeImage(argoappv1.KustomizeImage(image))
}
@@ -581,7 +566,7 @@ func readAppsFromStdin(apps *[]*argoappv1.Application) error {
func readAppsFromURI(fileURL string, apps *[]*argoappv1.Application) error {
readFilePayload := func() ([]byte, error) {
parsedURL, err := url.ParseRequestURI(fileURL)
- if err != nil || (parsedURL.Scheme != "http" && parsedURL.Scheme != "https") {
+ if err != nil || !(parsedURL.Scheme == "http" || parsedURL.Scheme == "https") {
return os.ReadFile(fileURL)
}
return config.ReadRemoteFile(fileURL)
@@ -617,11 +602,11 @@ func constructAppsBaseOnName(appName string, labels, annotations, args []string,
}
appName, appNs := argo.ParseFromQualifiedName(appName, "")
app = &argoappv1.Application{
- TypeMeta: metav1.TypeMeta{
+ TypeMeta: v1.TypeMeta{
Kind: application.ApplicationKind,
APIVersion: application.Group + "/v1alpha1",
},
- ObjectMeta: metav1.ObjectMeta{
+ ObjectMeta: v1.ObjectMeta{
Name: appName,
Namespace: appNs,
},
@@ -636,7 +621,7 @@ func constructAppsBaseOnName(appName string, labels, annotations, args []string,
}, nil
}
-func constructAppsFromFileURL(fileURL, appName string, labels, annotations, args []string, appOpts AppOptions, flags *pflag.FlagSet) ([]*argoappv1.Application, error) {
+func constructAppsFromFileUrl(fileURL, appName string, labels, annotations, args []string, appOpts AppOptions, flags *pflag.FlagSet) ([]*argoappv1.Application, error) {
apps := make([]*argoappv1.Application, 0)
// read uri
err := readAppsFromURI(fileURL, &apps)
@@ -651,7 +636,7 @@ func constructAppsFromFileURL(fileURL, appName string, labels, annotations, args
app.Name = appName
}
if app.Name == "" {
- return nil, stderrors.New("app.Name is empty. --name argument can be used to provide app.Name")
+ return nil, fmt.Errorf("app.Name is empty. --name argument can be used to provide app.Name")
}
mergeLabels(app, labels)
@@ -670,7 +655,7 @@ func ConstructApps(fileURL, appName string, labels, annotations, args []string,
if fileURL == "-" {
return constructAppsFromStdin()
} else if fileURL != "" {
- return constructAppsFromFileURL(fileURL, appName, labels, annotations, args, appOpts, flags)
+ return constructAppsFromFileUrl(fileURL, appName, labels, annotations, args, appOpts, flags)
}
return constructAppsBaseOnName(appName, labels, annotations, args, appOpts, flags)
@@ -697,7 +682,7 @@ func ConstructSource(source *argoappv1.ApplicationSource, appOpts AppOptions, fl
var data []byte
// read uri
parsedURL, err := url.ParseRequestURI(appOpts.values)
- if err != nil || (parsedURL.Scheme != "http" && parsedURL.Scheme != "https") {
+ if err != nil || !(parsedURL.Scheme == "http" || parsedURL.Scheme == "https") {
data, err = os.ReadFile(appOpts.values)
} else {
data, err = config.ReadRemoteFile(appOpts.values)
@@ -774,14 +759,10 @@ func ConstructSource(source *argoappv1.ApplicationSource, appOpts AppOptions, fl
setKustomizeOpt(source, kustomizeOpts{commonAnnotations: parsedAnnotations})
case "kustomize-label-without-selector":
setKustomizeOpt(source, kustomizeOpts{labelWithoutSelector: appOpts.kustomizeLabelWithoutSelector})
- case "kustomize-label-include-templates":
- setKustomizeOpt(source, kustomizeOpts{labelIncludeTemplates: appOpts.kustomizeLabelIncludeTemplates})
case "kustomize-force-common-label":
setKustomizeOpt(source, kustomizeOpts{forceCommonLabels: appOpts.kustomizeForceCommonLabels})
case "kustomize-force-common-annotation":
setKustomizeOpt(source, kustomizeOpts{forceCommonAnnotations: appOpts.kustomizeForceCommonAnnotations})
- case "ignore-missing-components":
- setKustomizeOpt(source, kustomizeOpts{ignoreMissingComponents: appOpts.ignoreMissingComponents})
case "jsonnet-tla-str":
setJsonnetOpt(source, appOpts.jsonnetTlaStr, false)
case "jsonnet-tla-code":
@@ -914,10 +895,10 @@ func FilterResources(groupChanged bool, resources []*argoappv1.ResourceDiff, gro
filteredObjects = append(filteredObjects, deepCopy)
}
if len(filteredObjects) == 0 {
- return nil, stderrors.New("no matching resource found")
+ return nil, fmt.Errorf("No matching resource found")
}
if len(filteredObjects) > 1 && !all {
- return nil, stderrors.New("multiple resources match inputs, use the --all flag to patch multiple resources")
+ return nil, fmt.Errorf("Multiple resources match inputs. Use the --all flag to patch multiple resources")
}
return filteredObjects, nil
}
diff --git a/cmd/util/app_test.go b/cmd/util/app_test.go
index 0f767fbb70..46b4115033 100644
--- a/cmd/util/app_test.go
+++ b/cmd/util/app_test.go
@@ -10,7 +10,7 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
"k8s.io/apimachinery/pkg/util/intstr"
)
@@ -165,17 +165,6 @@ func Test_setKustomizeOpt(t *testing.T) {
setKustomizeOpt(&src, kustomizeOpts{commonLabels: map[string]string{"foo1": "bar1", "foo2": "bar2"}, labelWithoutSelector: true})
assert.Equal(t, &v1alpha1.ApplicationSourceKustomize{CommonLabels: map[string]string{"foo1": "bar1", "foo2": "bar2"}, LabelWithoutSelector: true}, src.Kustomize)
})
- t.Run("Label include templates", func(t *testing.T) {
- src := v1alpha1.ApplicationSource{}
- setKustomizeOpt(&src, kustomizeOpts{commonLabels: map[string]string{"foo1": "bar1", "foo2": "bar2"}, labelIncludeTemplates: true})
- assert.Equal(t, &v1alpha1.ApplicationSourceKustomize{CommonLabels: map[string]string{"foo1": "bar1", "foo2": "bar2"}, LabelIncludeTemplates: true}, src.Kustomize)
- })
- t.Run("IgnoreMissingComponents", func(t *testing.T) {
- src := v1alpha1.ApplicationSource{}
- setKustomizeOpt(&src, kustomizeOpts{ignoreMissingComponents: true})
- t.Logf("HERE IS THE SOURCE\n %+v\n", src)
- assert.True(t, src.Kustomize.IgnoreMissingComponents)
- })
}
func Test_setJsonnetOpt(t *testing.T) {
@@ -554,7 +543,7 @@ func TestFilterResources(t *testing.T) {
}
filteredResources, err := FilterResources(false, resources, "g", "Service", "argocd-unknown", "test-helm", true)
- require.ErrorContains(t, err, "no matching resource found")
+ require.ErrorContains(t, err, "No matching resource found")
assert.Nil(t, filteredResources)
})
@@ -569,7 +558,7 @@ func TestFilterResources(t *testing.T) {
}
filteredResources, err := FilterResources(false, resources, "g", "Service", "argocd", "test-helm", false)
- require.ErrorContains(t, err, "use the --all flag")
+ require.ErrorContains(t, err, "Use the --all flag")
assert.Nil(t, filteredResources)
})
}
diff --git a/cmd/util/applicationset.go b/cmd/util/applicationset.go
index edf7718485..6f6fd1e3de 100644
--- a/cmd/util/applicationset.go
+++ b/cmd/util/applicationset.go
@@ -7,18 +7,18 @@ import (
"github.com/argoproj/gitops-engine/pkg/utils/kube"
- argoprojiov1alpha1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- "github.com/argoproj/argo-cd/v3/util/config"
+ argoprojiov1alpha1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/util/config"
)
func ConstructApplicationSet(fileURL string) ([]*argoprojiov1alpha1.ApplicationSet, error) {
if fileURL != "" {
- return constructAppsetFromFileURL(fileURL)
+ return constructAppsetFromFileUrl(fileURL)
}
return nil, nil
}
-func constructAppsetFromFileURL(fileURL string) ([]*argoprojiov1alpha1.ApplicationSet, error) {
+func constructAppsetFromFileUrl(fileURL string) ([]*argoprojiov1alpha1.ApplicationSet, error) {
appset := make([]*argoprojiov1alpha1.ApplicationSet, 0)
// read uri
err := readAppsetFromURI(fileURL, &appset)
@@ -32,7 +32,7 @@ func constructAppsetFromFileURL(fileURL string) ([]*argoprojiov1alpha1.Applicati
func readAppsetFromURI(fileURL string, appset *[]*argoprojiov1alpha1.ApplicationSet) error {
readFilePayload := func() ([]byte, error) {
parsedURL, err := url.ParseRequestURI(fileURL)
- if err != nil || (parsedURL.Scheme != "http" && parsedURL.Scheme != "https") {
+ if err != nil || !(parsedURL.Scheme == "http" || parsedURL.Scheme == "https") {
return os.ReadFile(fileURL)
}
return config.ReadRemoteFile(fileURL)
diff --git a/cmd/util/applicationset_test.go b/cmd/util/applicationset_test.go
index 45255fd6d3..0fdc0a9f89 100644
--- a/cmd/util/applicationset_test.go
+++ b/cmd/util/applicationset_test.go
@@ -5,7 +5,7 @@ import (
"github.com/stretchr/testify/assert"
- argoprojiov1alpha1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ argoprojiov1alpha1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
)
var appSet = `apiVersion: argoproj.io/v1alpha1
diff --git a/cmd/util/cluster.go b/cmd/util/cluster.go
index d674525c97..ab4e4816cf 100644
--- a/cmd/util/cluster.go
+++ b/cmd/util/cluster.go
@@ -2,7 +2,6 @@ package util
import (
"context"
- stderrors "errors"
"fmt"
"os"
"sort"
@@ -17,8 +16,8 @@ import (
clientcmdapiv1 "k8s.io/client-go/tools/clientcmd/api/v1"
"sigs.k8s.io/yaml"
- argoappv1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- "github.com/argoproj/argo-cd/v3/util/errors"
+ argoappv1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/util/errors"
)
type ClusterEndpoint string
@@ -70,24 +69,24 @@ func PrintKubeContexts(ca clientcmd.ConfigAccess) {
func NewCluster(name string, namespaces []string, clusterResources bool, conf *rest.Config, managerBearerToken string, awsAuthConf *argoappv1.AWSAuthConfig, execProviderConf *argoappv1.ExecProviderConfig, labels, annotations map[string]string) *argoappv1.Cluster {
tlsClientConfig := argoappv1.TLSClientConfig{
- Insecure: conf.Insecure,
- ServerName: conf.ServerName,
- CAData: conf.CAData,
- CertData: conf.CertData,
- KeyData: conf.KeyData,
+ Insecure: conf.TLSClientConfig.Insecure,
+ ServerName: conf.TLSClientConfig.ServerName,
+ CAData: conf.TLSClientConfig.CAData,
+ CertData: conf.TLSClientConfig.CertData,
+ KeyData: conf.TLSClientConfig.KeyData,
}
- if len(conf.CAData) == 0 && conf.CAFile != "" {
- data, err := os.ReadFile(conf.CAFile)
+ if len(conf.TLSClientConfig.CAData) == 0 && conf.TLSClientConfig.CAFile != "" {
+ data, err := os.ReadFile(conf.TLSClientConfig.CAFile)
errors.CheckError(err)
tlsClientConfig.CAData = data
}
- if len(conf.CertData) == 0 && conf.CertFile != "" {
- data, err := os.ReadFile(conf.CertFile)
+ if len(conf.TLSClientConfig.CertData) == 0 && conf.TLSClientConfig.CertFile != "" {
+ data, err := os.ReadFile(conf.TLSClientConfig.CertFile)
errors.CheckError(err)
tlsClientConfig.CertData = data
}
- if len(conf.KeyData) == 0 && conf.KeyFile != "" {
- data, err := os.ReadFile(conf.KeyFile)
+ if len(conf.TLSClientConfig.KeyData) == 0 && conf.TLSClientConfig.KeyFile != "" {
+ data, err := os.ReadFile(conf.TLSClientConfig.KeyFile)
errors.CheckError(err)
tlsClientConfig.KeyData = data
}
@@ -123,30 +122,28 @@ func NewCluster(name string, namespaces []string, clusterResources bool, conf *r
return &clst
}
-// GetKubePublicEndpoint returns the kubernetes apiserver endpoint and certificate authority data as published
+// GetKubePublicEndpoint returns the kubernetes apiserver endpoint as published
// in the kube-public.
-func GetKubePublicEndpoint(client kubernetes.Interface) (string, []byte, error) {
+func GetKubePublicEndpoint(client kubernetes.Interface) (string, error) {
clusterInfo, err := client.CoreV1().ConfigMaps("kube-public").Get(context.TODO(), "cluster-info", metav1.GetOptions{})
if err != nil {
- return "", nil, err
+ return "", err
}
kubeconfig, ok := clusterInfo.Data["kubeconfig"]
if !ok {
- return "", nil, stderrors.New("cluster-info does not contain a public kubeconfig")
+ return "", fmt.Errorf("cluster-info does not contain a public kubeconfig")
}
// Parse Kubeconfig and get server address
config := &clientcmdapiv1.Config{}
err = yaml.Unmarshal([]byte(kubeconfig), config)
if err != nil {
- return "", nil, fmt.Errorf("failed to parse cluster-info kubeconfig: %w", err)
+ return "", fmt.Errorf("failed to parse cluster-info kubeconfig: %w", err)
}
if len(config.Clusters) == 0 {
- return "", nil, stderrors.New("cluster-info kubeconfig does not have any clusters")
+ return "", fmt.Errorf("cluster-info kubeconfig does not have any clusters")
}
- endpoint := config.Clusters[0].Cluster.Server
- certificateAuthorityData := config.Clusters[0].Cluster.CertificateAuthorityData
- return endpoint, certificateAuthorityData, nil
+ return config.Clusters[0].Cluster.Server, nil
}
type ClusterOptions struct {
@@ -169,7 +166,7 @@ type ClusterOptions struct {
ExecProviderInstallHint string
ClusterEndpoint string
DisableCompression bool
- ProxyUrl string //nolint:revive //FIXME(var-naming)
+ ProxyUrl string
}
// InClusterEndpoint returns true if ArgoCD should reference the in-cluster
diff --git a/cmd/util/cluster_test.go b/cmd/util/cluster_test.go
index 3706b2d7df..12ed3fe5cc 100644
--- a/cmd/util/cluster_test.go
+++ b/cmd/util/cluster_test.go
@@ -13,7 +13,7 @@ import (
clientcmdapiv1 "k8s.io/client-go/tools/clientcmd/api/v1"
"sigs.k8s.io/yaml"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
)
func Test_newCluster(t *testing.T) {
@@ -35,7 +35,7 @@ func Test_newCluster(t *testing.T) {
assert.Equal(t, "test-cert-data", string(clusterWithData.Config.CertData))
assert.Equal(t, "test-key-data", string(clusterWithData.Config.KeyData))
- assert.Empty(t, clusterWithData.Config.BearerToken)
+ assert.Equal(t, "", clusterWithData.Config.BearerToken)
assert.Equal(t, labels, clusterWithData.Labels)
assert.Equal(t, annotations, clusterWithData.Annotations)
assert.False(t, clusterWithData.Config.DisableCompression)
@@ -56,7 +56,7 @@ func Test_newCluster(t *testing.T) {
assert.Contains(t, string(clusterWithFiles.Config.CertData), "test-cert-data")
assert.Contains(t, string(clusterWithFiles.Config.KeyData), "test-key-data")
- assert.Empty(t, clusterWithFiles.Config.BearerToken)
+ assert.Equal(t, "", clusterWithFiles.Config.BearerToken)
assert.Equal(t, labels, clusterWithFiles.Labels)
assert.Nil(t, clusterWithFiles.Annotations)
@@ -96,23 +96,8 @@ func TestGetKubePublicEndpoint(t *testing.T) {
name string
clusterInfo *corev1.ConfigMap
expectedEndpoint string
- expectedCAData []byte
expectError bool
}{
- {
- name: "has public endpoint and certificate authority data",
- clusterInfo: &corev1.ConfigMap{
- ObjectMeta: metav1.ObjectMeta{
- Namespace: "kube-public",
- Name: "cluster-info",
- },
- Data: map[string]string{
- "kubeconfig": kubeconfigFixture("https://test-cluster:6443", []byte("test-ca-data")),
- },
- },
- expectedEndpoint: "https://test-cluster:6443",
- expectedCAData: []byte("test-ca-data"),
- },
{
name: "has public endpoint",
clusterInfo: &corev1.ConfigMap{
@@ -121,11 +106,10 @@ func TestGetKubePublicEndpoint(t *testing.T) {
Name: "cluster-info",
},
Data: map[string]string{
- "kubeconfig": kubeconfigFixture("https://test-cluster:6443", nil),
+ "kubeconfig": kubeconfigFixture("https://test-cluster:6443"),
},
},
expectedEndpoint: "https://test-cluster:6443",
- expectedCAData: nil,
},
{
name: "no cluster-info",
@@ -152,7 +136,7 @@ func TestGetKubePublicEndpoint(t *testing.T) {
Name: "cluster-info",
},
Data: map[string]string{
- "kubeconfig": kubeconfigFixture("", nil),
+ "kubeconfig": kubeconfigFixture(""),
},
},
expectError: true,
@@ -179,27 +163,25 @@ func TestGetKubePublicEndpoint(t *testing.T) {
objects = append(objects, tc.clusterInfo)
}
clientset := fake.NewClientset(objects...)
- endpoint, caData, err := GetKubePublicEndpoint(clientset)
+ endpoint, err := GetKubePublicEndpoint(clientset)
if tc.expectError {
require.Error(t, err)
} else {
require.NoError(t, err)
}
require.Equalf(t, tc.expectedEndpoint, endpoint, "expected endpoint %s, got %s", tc.expectedEndpoint, endpoint)
- require.Equalf(t, tc.expectedCAData, caData, "expected caData %s, got %s", tc.expectedCAData, caData)
})
}
}
-func kubeconfigFixture(endpoint string, certificateAuthorityData []byte) string {
+func kubeconfigFixture(endpoint string) string {
kubeconfig := &clientcmdapiv1.Config{}
if len(endpoint) > 0 {
kubeconfig.Clusters = []clientcmdapiv1.NamedCluster{
{
Name: "test-kube",
Cluster: clientcmdapiv1.Cluster{
- Server: endpoint,
- CertificateAuthorityData: certificateAuthorityData,
+ Server: endpoint,
},
},
}
diff --git a/cmd/util/common.go b/cmd/util/common.go
index b4312e5836..7c7b629ab4 100644
--- a/cmd/util/common.go
+++ b/cmd/util/common.go
@@ -1,39 +1,6 @@
package util
-import (
- stderrors "errors"
-)
-
var (
LogFormat string
LogLevel string
)
-
-func ValidateBearerTokenForHTTPSRepoOnly(bearerToken string, isHTTPS bool) error {
- // Bearer token is only valid for HTTPS repositories
- if bearerToken != "" {
- if !isHTTPS {
- err := stderrors.New("--bearer-token is only supported for HTTPS repositories")
- return err
- }
- }
- return nil
-}
-
-func ValidateBearerTokenForGitOnly(bearerToken string, repoType string) error {
- // Bearer token is only valid for Git repositories
- if bearerToken != "" && repoType != "git" {
- err := stderrors.New("--bearer-token is only supported for Git repositories")
- return err
- }
- return nil
-}
-
-func ValidateBearerTokenAndPasswordCombo(bearerToken string, password string) error {
- // Either the password or the bearer token must be set, but not both
- if bearerToken != "" && password != "" {
- err := stderrors.New("only --bearer-token or --password is allowed, not both")
- return err
- }
- return nil
-}
diff --git a/cmd/util/common_test.go b/cmd/util/common_test.go
deleted file mode 100644
index c6950ab84f..0000000000
--- a/cmd/util/common_test.go
+++ /dev/null
@@ -1,155 +0,0 @@
-package util
-
-import (
- "testing"
-
- "github.com/stretchr/testify/require"
-)
-
-func TestValidateBearerTokenAndPasswordCombo(t *testing.T) {
- tests := []struct {
- name string
- bearerToken string
- password string
- expectError bool
- errorMsg string
- }{
- {
- name: "Both token and password set",
- bearerToken: "some-token",
- password: "some-password",
- expectError: true,
- errorMsg: "only --bearer-token or --password is allowed, not both",
- },
- {
- name: "Only token set",
- bearerToken: "some-token",
- password: "",
- expectError: false,
- },
- {
- name: "Only password set",
- bearerToken: "",
- password: "some-password",
- expectError: false,
- },
- {
- name: "Neither token nor password set",
- bearerToken: "",
- password: "",
- expectError: false,
- },
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- err := ValidateBearerTokenAndPasswordCombo(tt.bearerToken, tt.password)
- if tt.expectError {
- require.ErrorContains(t, err, tt.errorMsg)
- } else {
- require.NoError(t, err)
- }
- })
- }
-}
-
-func TestValidateBearerTokenForGitOnly(t *testing.T) {
- tests := []struct {
- name string
- bearerToken string
- repoType string
- expectError bool
- errorMsg string
- }{
- {
- name: "Bearer token with helm repo",
- bearerToken: "some-token",
- repoType: "helm",
- expectError: true,
- errorMsg: "--bearer-token is only supported for Git repositories",
- },
- {
- name: "Bearer token with git repo",
- bearerToken: "some-token",
- repoType: "git",
- expectError: false,
- },
- {
- name: "No bearer token with helm repo",
- bearerToken: "",
- repoType: "helm",
- expectError: false,
- },
- {
- name: "No bearer token with git repo",
- bearerToken: "",
- repoType: "git",
- expectError: false,
- },
- {
- name: "Bearer token with empty repo",
- bearerToken: "some-token",
- repoType: "",
- expectError: true,
- errorMsg: "--bearer-token is only supported for Git repositories",
- },
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- err := ValidateBearerTokenForGitOnly(tt.bearerToken, tt.repoType)
- if tt.expectError {
- require.ErrorContains(t, err, tt.errorMsg)
- } else {
- require.NoError(t, err)
- }
- })
- }
-}
-
-func TestValidateBearerTokenForHTTPSRepoOnly(t *testing.T) {
- tests := []struct {
- name string
- bearerToken string
- isHTTPS bool
- expectError bool
- errorMsg string
- }{
- {
- name: "Bearer token with HTTPS repo",
- bearerToken: "some-token",
- isHTTPS: true,
- expectError: false,
- },
- {
- name: "Bearer token with non-HTTPS repo",
- bearerToken: "some-token",
- isHTTPS: false,
- expectError: true,
- errorMsg: "--bearer-token is only supported for HTTPS repositories",
- },
- {
- name: "No bearer token with HTTPS repo",
- bearerToken: "",
- isHTTPS: true,
- expectError: false,
- },
- {
- name: "No bearer token with non-HTTPS repo",
- bearerToken: "",
- isHTTPS: false,
- expectError: false,
- },
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- err := ValidateBearerTokenForHTTPSRepoOnly(tt.bearerToken, tt.isHTTPS)
- if tt.expectError {
- require.ErrorContains(t, err, tt.errorMsg)
- } else {
- require.NoError(t, err)
- }
- })
- }
-}
diff --git a/cmd/util/project.go b/cmd/util/project.go
index c86bbdc018..63dff2018c 100644
--- a/cmd/util/project.go
+++ b/cmd/util/project.go
@@ -10,13 +10,13 @@ import (
"github.com/spf13/cobra"
"github.com/spf13/pflag"
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+ v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/utils/ptr"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- "github.com/argoproj/argo-cd/v3/util/config"
- "github.com/argoproj/argo-cd/v3/util/gpg"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/util/config"
+ "github.com/argoproj/argo-cd/v2/util/gpg"
)
type ProjectOpts struct {
@@ -52,31 +52,31 @@ func AddProjFlags(command *cobra.Command, opts *ProjectOpts) {
"Destination server, namespace and target service account (e.g. https://192.168.99.100:8443,default,default-sa)")
}
-func getGroupKindList(values []string) []metav1.GroupKind {
- var res []metav1.GroupKind
+func getGroupKindList(values []string) []v1.GroupKind {
+ var res []v1.GroupKind
for _, val := range values {
if parts := strings.Split(val, "/"); len(parts) == 2 {
- res = append(res, metav1.GroupKind{Group: parts[0], Kind: parts[1]})
+ res = append(res, v1.GroupKind{Group: parts[0], Kind: parts[1]})
} else if len(parts) == 1 {
- res = append(res, metav1.GroupKind{Kind: parts[0]})
+ res = append(res, v1.GroupKind{Kind: parts[0]})
}
}
return res
}
-func (opts *ProjectOpts) GetAllowedClusterResources() []metav1.GroupKind {
+func (opts *ProjectOpts) GetAllowedClusterResources() []v1.GroupKind {
return getGroupKindList(opts.allowedClusterResources)
}
-func (opts *ProjectOpts) GetDeniedClusterResources() []metav1.GroupKind {
+func (opts *ProjectOpts) GetDeniedClusterResources() []v1.GroupKind {
return getGroupKindList(opts.deniedClusterResources)
}
-func (opts *ProjectOpts) GetAllowedNamespacedResources() []metav1.GroupKind {
+func (opts *ProjectOpts) GetAllowedNamespacedResources() []v1.GroupKind {
return getGroupKindList(opts.allowedNamespacedResources)
}
-func (opts *ProjectOpts) GetDeniedNamespacedResources() []metav1.GroupKind {
+func (opts *ProjectOpts) GetDeniedNamespacedResources() []v1.GroupKind {
return getGroupKindList(opts.deniedNamespacedResources)
}
@@ -86,11 +86,12 @@ 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
}
@@ -101,12 +102,13 @@ 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
}
@@ -150,7 +152,7 @@ func readProjFromStdin(proj *v1alpha1.AppProject) error {
func readProjFromURI(fileURL string, proj *v1alpha1.AppProject) error {
parsedURL, err := url.ParseRequestURI(fileURL)
- if err != nil || (parsedURL.Scheme != "http" && parsedURL.Scheme != "https") {
+ if err != nil || !(parsedURL.Scheme == "http" || parsedURL.Scheme == "https") {
err = config.UnmarshalLocalFile(fileURL, &proj)
} else {
err = config.UnmarshalRemoteFile(fileURL, &proj)
@@ -197,19 +199,18 @@ func SetProjSpecOptions(flags *pflag.FlagSet, spec *v1alpha1.AppProjectSpec, pro
func ConstructAppProj(fileURL string, args []string, opts ProjectOpts, c *cobra.Command) (*v1alpha1.AppProject, error) {
proj := v1alpha1.AppProject{
- TypeMeta: metav1.TypeMeta{
+ TypeMeta: v1.TypeMeta{
Kind: application.AppProjectKind,
APIVersion: application.Group + "/v1alpha1",
},
}
- switch {
- case fileURL == "-":
+ if fileURL == "-" {
// read stdin
err := readProjFromStdin(&proj)
if err != nil {
return nil, err
}
- case fileURL != "":
+ } else if fileURL != "" {
// read uri
err := readProjFromURI(fileURL, &proj)
if err != nil {
@@ -219,7 +220,7 @@ func ConstructAppProj(fileURL string, args []string, opts ProjectOpts, c *cobra.
if len(args) == 1 && args[0] != proj.Name {
return nil, fmt.Errorf("project name '%s' does not match project spec metadata.name '%s'", args[0], proj.Name)
}
- default:
+ } else {
// read arguments
if len(args) == 0 {
c.HelpFunc()(c, args)
diff --git a/cmd/util/project_test.go b/cmd/util/project_test.go
index dea5cabb2c..83f5974b6c 100644
--- a/cmd/util/project_test.go
+++ b/cmd/util/project_test.go
@@ -4,9 +4,9 @@ import (
"testing"
"github.com/stretchr/testify/assert"
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+ v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
)
func TestProjectOpts_ResourceLists(t *testing.T) {
@@ -17,10 +17,14 @@ func TestProjectOpts_ResourceLists(t *testing.T) {
deniedClusterResources: []string{"rbac.authorization.k8s.io/ClusterRole"},
}
- assert.ElementsMatch(t, []metav1.GroupKind{{Kind: "ConfigMap"}}, opts.GetAllowedNamespacedResources())
- assert.ElementsMatch(t, []metav1.GroupKind{{Group: "apps", Kind: "DaemonSet"}}, opts.GetDeniedNamespacedResources())
- assert.ElementsMatch(t, []metav1.GroupKind{{Group: "apiextensions.k8s.io", Kind: "CustomResourceDefinition"}}, opts.GetAllowedClusterResources())
- assert.ElementsMatch(t, []metav1.GroupKind{{Group: "rbac.authorization.k8s.io", Kind: "ClusterRole"}}, opts.GetDeniedClusterResources())
+ assert.ElementsMatch(t,
+ []v1.GroupKind{{Kind: "ConfigMap"}}, opts.GetAllowedNamespacedResources())
+ assert.ElementsMatch(t,
+ []v1.GroupKind{{Group: "apps", Kind: "DaemonSet"}}, opts.GetDeniedNamespacedResources())
+ assert.ElementsMatch(t,
+ []v1.GroupKind{{Group: "apiextensions.k8s.io", Kind: "CustomResourceDefinition"}}, opts.GetAllowedClusterResources())
+ assert.ElementsMatch(t,
+ []v1.GroupKind{{Group: "rbac.authorization.k8s.io", Kind: "ClusterRole"}}, opts.GetDeniedClusterResources())
}
func TestProjectOpts_GetDestinationServiceAccounts(t *testing.T) {
diff --git a/cmd/util/repo.go b/cmd/util/repo.go
index a46951071d..d87d428367 100644
--- a/cmd/util/repo.go
+++ b/cmd/util/repo.go
@@ -3,18 +3,18 @@ package util
import (
"github.com/spf13/cobra"
- "github.com/argoproj/argo-cd/v3/common"
- appsv1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/common"
+ appsv1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
)
type RepoOptions struct {
Repo appsv1.Repository
Upsert bool
- SshPrivateKeyPath string //nolint:revive //FIXME(var-naming)
+ SshPrivateKeyPath string
InsecureIgnoreHostKey bool
InsecureSkipServerVerification bool
- TlsClientCertPath string //nolint:revive //FIXME(var-naming)
- TlsClientCertKeyPath string //nolint:revive //FIXME(var-naming)
+ TlsClientCertPath string
+ TlsClientCertKeyPath string
EnableLfs bool
EnableOci bool
GithubAppId int64
@@ -24,8 +24,7 @@ type RepoOptions struct {
Proxy string
NoProxy string
GCPServiceAccountKeyPath string
- ForceHttpBasicAuth bool //nolint:revive //FIXME(var-naming)
- UseAzureWorkloadIdentity bool
+ ForceHttpBasicAuth bool
}
func AddRepoFlags(command *cobra.Command, opts *RepoOptions) {
@@ -34,7 +33,6 @@ func AddRepoFlags(command *cobra.Command, opts *RepoOptions) {
command.Flags().StringVar(&opts.Repo.Project, "project", "", "project of the repository")
command.Flags().StringVar(&opts.Repo.Username, "username", "", "username to the repository")
command.Flags().StringVar(&opts.Repo.Password, "password", "", "password to the repository")
- command.Flags().StringVar(&opts.Repo.BearerToken, "bearer-token", "", "bearer token to the Git BitBucket Data Center repository")
command.Flags().StringVar(&opts.SshPrivateKeyPath, "ssh-private-key-path", "", "path to the private ssh key (e.g. ~/.ssh/id_rsa)")
command.Flags().StringVar(&opts.TlsClientCertPath, "tls-client-cert-path", "", "path to the TLS client cert (must be PEM format)")
command.Flags().StringVar(&opts.TlsClientCertKeyPath, "tls-client-cert-key-path", "", "path to the TLS client cert's key path (must be PEM format)")
@@ -50,5 +48,4 @@ func AddRepoFlags(command *cobra.Command, opts *RepoOptions) {
command.Flags().StringVar(&opts.NoProxy, "no-proxy", "", "don't access these targets via proxy")
command.Flags().StringVar(&opts.GCPServiceAccountKeyPath, "gcp-service-account-key-path", "", "service account key for the Google Cloud Platform")
command.Flags().BoolVar(&opts.ForceHttpBasicAuth, "force-http-basic-auth", false, "whether to force use of basic auth when connecting repository via HTTP")
- command.Flags().BoolVar(&opts.UseAzureWorkloadIdentity, "use-azure-workload-identity", false, "whether to use azure workload identity for authentication")
}
diff --git a/cmpserver/apiclient/clientset.go b/cmpserver/apiclient/clientset.go
index fb751850e6..8e3ff9b856 100644
--- a/cmpserver/apiclient/clientset.go
+++ b/cmpserver/apiclient/clientset.go
@@ -5,16 +5,17 @@ import (
"math"
"time"
- "github.com/argoproj/argo-cd/v3/common"
- "github.com/argoproj/argo-cd/v3/util/env"
+ "github.com/argoproj/argo-cd/v2/common"
+ "github.com/argoproj/argo-cd/v2/util/env"
- grpc_retry "github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/retry"
+ grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
+ grpc_retry "github.com/grpc-ecosystem/go-grpc-middleware/retry"
log "github.com/sirupsen/logrus"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
- grpc_util "github.com/argoproj/argo-cd/v3/util/grpc"
- utilio "github.com/argoproj/argo-cd/v3/util/io"
+ grpc_util "github.com/argoproj/argo-cd/v2/util/grpc"
+ "github.com/argoproj/argo-cd/v2/util/io"
)
// MaxGRPCMessageSize contains max grpc message size
@@ -22,14 +23,14 @@ var MaxGRPCMessageSize = env.ParseNumFromEnv(common.EnvGRPCMaxSizeMB, 100, 0, ma
// Clientset represents config management plugin server api clients
type Clientset interface {
- NewConfigManagementPluginClient() (utilio.Closer, ConfigManagementPluginServiceClient, error)
+ NewConfigManagementPluginClient() (io.Closer, ConfigManagementPluginServiceClient, error)
}
type clientSet struct {
address string
}
-func (c *clientSet) NewConfigManagementPluginClient() (utilio.Closer, ConfigManagementPluginServiceClient, error) {
+func (c *clientSet) NewConfigManagementPluginClient() (io.Closer, ConfigManagementPluginServiceClient, error) {
conn, err := NewConnection(c.address)
if err != nil {
return nil, nil, err
@@ -45,7 +46,7 @@ func NewConnection(address string) (*grpc.ClientConn, error) {
unaryInterceptors := []grpc.UnaryClientInterceptor{grpc_retry.UnaryClientInterceptor(retryOpts...)}
dialOpts := []grpc.DialOption{
grpc.WithStreamInterceptor(grpc_retry.StreamClientInterceptor(retryOpts...)),
- grpc.WithChainUnaryInterceptor(unaryInterceptors...),
+ grpc.WithUnaryInterceptor(grpc_middleware.ChainUnaryClient(unaryInterceptors...)),
grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(MaxGRPCMessageSize), grpc.MaxCallSendMsgSize(MaxGRPCMessageSize)),
grpc.WithUnaryInterceptor(grpc_util.OTELUnaryClientInterceptor()),
grpc.WithStreamInterceptor(grpc_util.OTELStreamClientInterceptor()),
diff --git a/cmpserver/apiclient/plugin.pb.go b/cmpserver/apiclient/plugin.pb.go
index ed46f6f864..5e60bcfabe 100644
--- a/cmpserver/apiclient/plugin.pb.go
+++ b/cmpserver/apiclient/plugin.pb.go
@@ -6,7 +6,7 @@ package apiclient
import (
context "context"
fmt "fmt"
- apiclient "github.com/argoproj/argo-cd/v3/reposerver/apiclient"
+ apiclient "github.com/argoproj/argo-cd/v2/reposerver/apiclient"
proto "github.com/gogo/protobuf/proto"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
@@ -538,49 +538,49 @@ func init() {
func init() { proto.RegisterFile("cmpserver/plugin/plugin.proto", fileDescriptor_b21875a7079a06ed) }
var fileDescriptor_b21875a7079a06ed = []byte{
- // 668 bytes of a gzipped FileDescriptorProto
- 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x84, 0x54, 0xcd, 0x6e, 0xd3, 0x40,
- 0x10, 0x8e, 0x9b, 0xb4, 0x4d, 0x26, 0x95, 0x1a, 0xad, 0xa0, 0x98, 0xd0, 0x86, 0xe0, 0x03, 0xca,
- 0x05, 0x47, 0x4a, 0x7b, 0x45, 0xa2, 0x2d, 0xa1, 0x15, 0x28, 0x28, 0x72, 0xb9, 0xc0, 0x01, 0x69,
- 0xe3, 0x4c, 0x92, 0xa5, 0xf6, 0xee, 0xb2, 0x5e, 0x5b, 0x0a, 0x5c, 0x10, 0x2f, 0xc3, 0xab, 0x70,
- 0xe4, 0x11, 0x50, 0x5f, 0x83, 0x0b, 0xf2, 0xda, 0x4e, 0xa2, 0x36, 0x6d, 0x4f, 0x9e, 0xbf, 0xfd,
- 0xfc, 0xcd, 0xec, 0x37, 0x0b, 0x07, 0x7e, 0x28, 0x23, 0x54, 0x09, 0xaa, 0xae, 0x0c, 0xe2, 0x29,
- 0xe3, 0xf9, 0xc7, 0x95, 0x4a, 0x68, 0x41, 0xb6, 0x32, 0xaf, 0xd9, 0x9f, 0x32, 0x3d, 0x8b, 0x47,
- 0xae, 0x2f, 0xc2, 0x2e, 0x55, 0x53, 0x21, 0x95, 0xf8, 0x62, 0x8c, 0x17, 0xfe, 0xb8, 0x9b, 0x1c,
- 0x76, 0x15, 0x4a, 0x91, 0xc3, 0x18, 0x93, 0x69, 0xa1, 0xe6, 0x2b, 0x66, 0x06, 0xd7, 0x7c, 0x32,
- 0x15, 0x62, 0x1a, 0x60, 0xd7, 0x78, 0xa3, 0x78, 0xd2, 0xc5, 0x50, 0xea, 0x3c, 0xe9, 0xfc, 0xb0,
- 0xa0, 0x71, 0x2c, 0xe5, 0x85, 0x56, 0x48, 0x43, 0x0f, 0xbf, 0xc6, 0x18, 0x69, 0xf2, 0x12, 0xaa,
- 0x21, 0x6a, 0x3a, 0xa6, 0x9a, 0xda, 0x56, 0xdb, 0xea, 0xd4, 0x7b, 0x4f, 0xdd, 0x9c, 0xe1, 0x80,
- 0x72, 0x36, 0xc1, 0x48, 0xe7, 0xa5, 0x83, 0xbc, 0xec, 0xbc, 0xe4, 0x2d, 0x8e, 0x10, 0x07, 0x2a,
- 0x13, 0x16, 0xa0, 0xbd, 0x61, 0x8e, 0xee, 0x14, 0x47, 0xdf, 0xb0, 0x00, 0xcf, 0x4b, 0x9e, 0xc9,
- 0x9d, 0xd4, 0x60, 0x5b, 0x65, 0x10, 0xce, 0x2f, 0x0b, 0x1e, 0xdd, 0x02, 0x4b, 0x6c, 0xd8, 0xa6,
- 0x52, 0xbe, 0xa7, 0x21, 0x1a, 0x22, 0x35, 0xaf, 0x70, 0x49, 0x0b, 0x80, 0x4a, 0xe9, 0x61, 0x30,
- 0xa4, 0x7a, 0x66, 0x7e, 0x55, 0xf3, 0x56, 0x22, 0xa4, 0x09, 0x55, 0x7f, 0x86, 0xfe, 0x65, 0x14,
- 0x87, 0x76, 0xd9, 0x64, 0x17, 0x3e, 0x21, 0x50, 0x89, 0xd8, 0x37, 0xb4, 0x2b, 0x6d, 0xab, 0x53,
- 0xf6, 0x8c, 0x4d, 0x1c, 0x28, 0x23, 0x4f, 0xec, 0xcd, 0x76, 0xb9, 0x53, 0xef, 0x35, 0x0a, 0xce,
- 0x7d, 0x9e, 0xf4, 0xb9, 0x56, 0x73, 0x2f, 0x4d, 0x3a, 0x47, 0x50, 0x2d, 0x02, 0x29, 0x06, 0x5f,
- 0xd2, 0x32, 0x36, 0x79, 0x00, 0x9b, 0x09, 0x0d, 0x62, 0xcc, 0xe9, 0x64, 0x8e, 0x33, 0x84, 0xc6,
- 0xb2, 0xbd, 0x48, 0x0a, 0x1e, 0x21, 0xd9, 0x87, 0x5a, 0x98, 0xc7, 0x22, 0xdb, 0x6a, 0x97, 0x3b,
- 0x35, 0x6f, 0x19, 0x48, 0x7b, 0x8b, 0x44, 0xac, 0x7c, 0xfc, 0x30, 0x97, 0x05, 0xd8, 0x4a, 0xc4,
- 0x99, 0x00, 0xf1, 0x16, 0xb7, 0xbc, 0xc0, 0x6c, 0x43, 0x9d, 0x45, 0x17, 0xb1, 0x94, 0x42, 0x69,
- 0x1c, 0x1b, 0x62, 0x55, 0x6f, 0x35, 0x44, 0x5c, 0x20, 0x2c, 0x7a, 0xcd, 0x22, 0x5f, 0x24, 0xa8,
- 0xe6, 0x7d, 0x4e, 0x47, 0x01, 0x8e, 0x0d, 0x7e, 0xd5, 0x5b, 0x93, 0x71, 0xbe, 0x43, 0x6b, 0x48,
- 0x15, 0x0d, 0x51, 0xa3, 0x8a, 0x8e, 0x39, 0x17, 0x31, 0xf7, 0x31, 0x44, 0xbe, 0xec, 0xe3, 0x23,
- 0xec, 0xc9, 0xa2, 0x62, 0xb5, 0x20, 0x6b, 0xaa, 0xde, 0x7b, 0xe6, 0xae, 0xc8, 0x71, 0xb8, 0xae,
- 0xd2, 0xbb, 0x05, 0xc0, 0xd9, 0x87, 0x4a, 0xaa, 0x98, 0x74, 0xa8, 0xfe, 0x2c, 0xe6, 0x97, 0xa6,
- 0xa1, 0x1d, 0x2f, 0x73, 0x9c, 0x9f, 0x16, 0xb4, 0x4f, 0xd3, 0xfb, 0x1c, 0x9a, 0x8b, 0x3a, 0x15,
- 0x7c, 0xc2, 0xa6, 0xb1, 0xa2, 0x9a, 0x09, 0xbe, 0x60, 0x77, 0x04, 0x0f, 0x57, 0xba, 0x2a, 0x6a,
- 0x16, 0xb3, 0x59, 0x9f, 0x24, 0x1d, 0xd8, 0x95, 0x4a, 0x24, 0x6c, 0x8c, 0x67, 0x4c, 0x9f, 0x2a,
- 0x1c, 0x47, 0xf9, 0x88, 0xae, 0x87, 0x7b, 0xff, 0x36, 0xe0, 0x20, 0x3b, 0x38, 0xa0, 0x9c, 0x4e,
- 0x0d, 0xf1, 0x8c, 0xcf, 0x05, 0xaa, 0x84, 0xf9, 0x48, 0xde, 0x42, 0xe3, 0x0c, 0x39, 0x2a, 0xaa,
- 0xb1, 0xd0, 0x00, 0xb1, 0x0b, 0x71, 0x5d, 0xdf, 0xbb, 0xa6, 0x7d, 0x73, 0xcb, 0xb2, 0x4e, 0x9c,
- 0x52, 0xc7, 0x22, 0x9f, 0xc1, 0xbe, 0xad, 0x63, 0xb2, 0xe7, 0x66, 0x4b, 0xee, 0x16, 0x4b, 0xee,
- 0xf6, 0xd3, 0x25, 0x6f, 0x76, 0x0a, 0xc4, 0xfb, 0x66, 0xe5, 0x94, 0xc8, 0x3b, 0xd8, 0x1d, 0x50,
- 0xed, 0xcf, 0x96, 0xd2, 0xba, 0x83, 0x6a, 0xb3, 0xc8, 0xdc, 0x14, 0xa2, 0x21, 0x4b, 0xe1, 0xf1,
- 0x19, 0xea, 0xf5, 0xea, 0xb9, 0x03, 0xf6, 0x79, 0x91, 0xb9, 0x5b, 0x77, 0xe9, 0x2f, 0x4e, 0x5e,
- 0xfd, 0xbe, 0x6a, 0x59, 0x7f, 0xae, 0x5a, 0xd6, 0xdf, 0xab, 0x96, 0xf5, 0xa9, 0x77, 0xcf, 0x63,
- 0xb9, 0x7c, 0x72, 0xa9, 0x64, 0x7e, 0xc0, 0x90, 0xeb, 0xd1, 0x96, 0x99, 0xd6, 0xe1, 0xff, 0x00,
- 0x00, 0x00, 0xff, 0xff, 0xb0, 0x8d, 0xb8, 0x47, 0x90, 0x05, 0x00, 0x00,
+ // 670 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x84, 0x54, 0xcd, 0x6e, 0xd3, 0x4a,
+ 0x14, 0x8e, 0x9b, 0xb4, 0x4d, 0x4e, 0x2a, 0x35, 0x1a, 0xdd, 0xdb, 0xeb, 0x9b, 0xdb, 0xe6, 0x06,
+ 0x2f, 0x50, 0x36, 0x38, 0x52, 0xe8, 0x16, 0x89, 0xb6, 0x84, 0x56, 0xa0, 0xa0, 0xc8, 0x65, 0x03,
+ 0x0b, 0xa4, 0x89, 0x73, 0x92, 0x0c, 0xb5, 0x67, 0x86, 0xf1, 0xd8, 0x52, 0x60, 0x83, 0x78, 0x19,
+ 0x5e, 0x85, 0x25, 0x8f, 0x80, 0xfa, 0x1a, 0x6c, 0x90, 0xc7, 0x76, 0x62, 0xb5, 0x69, 0xbb, 0xf2,
+ 0xf9, 0x9b, 0xcf, 0xdf, 0x39, 0xf3, 0x9d, 0x81, 0x23, 0x3f, 0x94, 0x11, 0xaa, 0x04, 0x55, 0x5f,
+ 0x06, 0xf1, 0x9c, 0xf1, 0xfc, 0xe3, 0x4a, 0x25, 0xb4, 0x20, 0x3b, 0x99, 0xd7, 0x1e, 0xce, 0x99,
+ 0x5e, 0xc4, 0x13, 0xd7, 0x17, 0x61, 0x9f, 0xaa, 0xb9, 0x90, 0x4a, 0x7c, 0x34, 0xc6, 0x13, 0x7f,
+ 0xda, 0x4f, 0x06, 0x7d, 0x85, 0x52, 0xe4, 0x30, 0xc6, 0x64, 0x5a, 0xa8, 0x65, 0xc9, 0xcc, 0xe0,
+ 0xda, 0xff, 0xcd, 0x85, 0x98, 0x07, 0xd8, 0x37, 0xde, 0x24, 0x9e, 0xf5, 0x31, 0x94, 0x3a, 0x4f,
+ 0x3a, 0x5f, 0x2d, 0x68, 0x9d, 0x48, 0x79, 0xa9, 0x15, 0xd2, 0xd0, 0xc3, 0x4f, 0x31, 0x46, 0x9a,
+ 0x3c, 0x83, 0x7a, 0x88, 0x9a, 0x4e, 0xa9, 0xa6, 0xb6, 0xd5, 0xb5, 0x7a, 0xcd, 0xc1, 0xff, 0x6e,
+ 0xce, 0x70, 0x44, 0x39, 0x9b, 0x61, 0xa4, 0xf3, 0xd2, 0x51, 0x5e, 0x76, 0x51, 0xf1, 0x56, 0x47,
+ 0x88, 0x03, 0xb5, 0x19, 0x0b, 0xd0, 0xde, 0x32, 0x47, 0xf7, 0x8a, 0xa3, 0x2f, 0x59, 0x80, 0x17,
+ 0x15, 0xcf, 0xe4, 0x4e, 0x1b, 0xb0, 0xab, 0x32, 0x08, 0xe7, 0xbb, 0x05, 0xff, 0xdc, 0x01, 0x4b,
+ 0x6c, 0xd8, 0xa5, 0x52, 0xbe, 0xa1, 0x21, 0x1a, 0x22, 0x0d, 0xaf, 0x70, 0x49, 0x07, 0x80, 0x4a,
+ 0xe9, 0x61, 0x30, 0xa6, 0x7a, 0x61, 0x7e, 0xd5, 0xf0, 0x4a, 0x11, 0xd2, 0x86, 0xba, 0xbf, 0x40,
+ 0xff, 0x2a, 0x8a, 0x43, 0xbb, 0x6a, 0xb2, 0x2b, 0x9f, 0x10, 0xa8, 0x45, 0xec, 0x33, 0xda, 0xb5,
+ 0xae, 0xd5, 0xab, 0x7a, 0xc6, 0x26, 0x0e, 0x54, 0x91, 0x27, 0xf6, 0x76, 0xb7, 0xda, 0x6b, 0x0e,
+ 0x5a, 0x05, 0xe7, 0x21, 0x4f, 0x86, 0x5c, 0xab, 0xa5, 0x97, 0x26, 0x9d, 0x63, 0xa8, 0x17, 0x81,
+ 0x14, 0x83, 0xaf, 0x69, 0x19, 0x9b, 0xfc, 0x05, 0xdb, 0x09, 0x0d, 0x62, 0xcc, 0xe9, 0x64, 0x8e,
+ 0x33, 0x86, 0xd6, 0xba, 0xbd, 0x48, 0x0a, 0x1e, 0x21, 0x39, 0x84, 0x46, 0x98, 0xc7, 0x22, 0xdb,
+ 0xea, 0x56, 0x7b, 0x0d, 0x6f, 0x1d, 0x48, 0x7b, 0x8b, 0x44, 0xac, 0x7c, 0x7c, 0xbb, 0x94, 0x05,
+ 0x58, 0x29, 0xe2, 0xcc, 0x80, 0x78, 0xab, 0x5b, 0x5e, 0x61, 0x76, 0xa1, 0xc9, 0xa2, 0xcb, 0x58,
+ 0x4a, 0xa1, 0x34, 0x4e, 0x0d, 0xb1, 0xba, 0x57, 0x0e, 0x11, 0x17, 0x08, 0x8b, 0x5e, 0xb0, 0xc8,
+ 0x17, 0x09, 0xaa, 0xe5, 0x90, 0xd3, 0x49, 0x80, 0x53, 0x83, 0x5f, 0xf7, 0x36, 0x64, 0x9c, 0x2f,
+ 0xd0, 0x19, 0x53, 0x45, 0x43, 0xd4, 0xa8, 0xa2, 0x13, 0xce, 0x45, 0xcc, 0x7d, 0x0c, 0x91, 0xaf,
+ 0xfb, 0x78, 0x07, 0x07, 0xb2, 0xa8, 0x28, 0x17, 0x64, 0x4d, 0x35, 0x07, 0x8f, 0xdc, 0x92, 0x1c,
+ 0xc7, 0x9b, 0x2a, 0xbd, 0x3b, 0x00, 0x9c, 0x43, 0xa8, 0xa5, 0x8a, 0x49, 0x87, 0xea, 0x2f, 0x62,
+ 0x7e, 0x65, 0x1a, 0xda, 0xf3, 0x32, 0xc7, 0xf9, 0x66, 0x41, 0xf7, 0x2c, 0xbd, 0xcf, 0xb1, 0xb9,
+ 0xa8, 0x33, 0xc1, 0x67, 0x6c, 0x1e, 0x2b, 0xaa, 0x99, 0xe0, 0x2b, 0x76, 0xc7, 0xf0, 0x77, 0xa9,
+ 0xab, 0xa2, 0x66, 0x35, 0x9b, 0xcd, 0x49, 0xd2, 0x83, 0x7d, 0xa9, 0x44, 0xc2, 0xa6, 0x78, 0xce,
+ 0xf4, 0x99, 0xc2, 0x69, 0x94, 0x8f, 0xe8, 0x66, 0x78, 0xf0, 0x7b, 0x0b, 0x8e, 0xb2, 0x83, 0x23,
+ 0xca, 0xe9, 0xdc, 0x10, 0xcf, 0xf8, 0x5c, 0xa2, 0x4a, 0x98, 0x8f, 0xe4, 0x15, 0xb4, 0xce, 0x91,
+ 0xa3, 0xa2, 0x1a, 0x0b, 0x0d, 0x10, 0xbb, 0x10, 0xd7, 0xcd, 0xbd, 0x6b, 0xdb, 0xb7, 0xb7, 0x2c,
+ 0xeb, 0xc4, 0xa9, 0xf4, 0x2c, 0xf2, 0x01, 0xec, 0xbb, 0x3a, 0x26, 0x07, 0x6e, 0xb6, 0xe4, 0x6e,
+ 0xb1, 0xe4, 0xee, 0x30, 0x5d, 0xf2, 0x76, 0xaf, 0x40, 0x7c, 0x68, 0x56, 0x4e, 0x85, 0xbc, 0x86,
+ 0xfd, 0x11, 0xd5, 0xfe, 0x62, 0x2d, 0xad, 0x7b, 0xa8, 0xb6, 0x8b, 0xcc, 0x6d, 0x21, 0x1a, 0xb2,
+ 0x14, 0xfe, 0x3d, 0x47, 0xbd, 0x59, 0x3d, 0xf7, 0xc0, 0x3e, 0x2e, 0x32, 0xf7, 0xeb, 0x2e, 0xfd,
+ 0xc5, 0xe9, 0xf3, 0x1f, 0xd7, 0x1d, 0xeb, 0xe7, 0x75, 0xc7, 0xfa, 0x75, 0xdd, 0xb1, 0xde, 0x0f,
+ 0x1e, 0x78, 0x2c, 0xd7, 0x4f, 0x2e, 0x95, 0xcc, 0x0f, 0x18, 0x72, 0x3d, 0xd9, 0x31, 0xd3, 0x7a,
+ 0xfa, 0x27, 0x00, 0x00, 0xff, 0xff, 0xa3, 0xfa, 0x98, 0xfb, 0x90, 0x05, 0x00, 0x00,
}
// Reference imports to suppress errors if they are not otherwise used.
diff --git a/cmpserver/plugin/config.go b/cmpserver/plugin/config.go
index ed1ee8b5ea..949e212d9c 100644
--- a/cmpserver/plugin/config.go
+++ b/cmpserver/plugin/config.go
@@ -1,15 +1,14 @@
package plugin
import (
- "errors"
"fmt"
"strings"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
- "github.com/argoproj/argo-cd/v3/common"
- "github.com/argoproj/argo-cd/v3/reposerver/apiclient"
- configUtil "github.com/argoproj/argo-cd/v3/util/config"
+ "github.com/argoproj/argo-cd/v2/common"
+ "github.com/argoproj/argo-cd/v2/reposerver/apiclient"
+ configUtil "github.com/argoproj/argo-cd/v2/util/config"
)
const (
@@ -83,13 +82,13 @@ func ReadPluginConfig(filePath string) (*PluginConfig, error) {
func ValidatePluginConfig(config PluginConfig) error {
if config.Metadata.Name == "" {
- return errors.New("invalid plugin configuration file. metadata.name should be non-empty")
+ return fmt.Errorf("invalid plugin configuration file. metadata.name should be non-empty.")
}
- if config.Kind != ConfigManagementPluginKind {
- return fmt.Errorf("invalid plugin configuration file. kind should be %s, found %s", ConfigManagementPluginKind, config.Kind)
+ if config.TypeMeta.Kind != ConfigManagementPluginKind {
+ return fmt.Errorf("invalid plugin configuration file. kind should be %s, found %s", ConfigManagementPluginKind, config.TypeMeta.Kind)
}
if len(config.Spec.Generate.Command) == 0 {
- return errors.New("invalid plugin configuration file. spec.generate command should be non-empty")
+ return fmt.Errorf("invalid plugin configuration file. spec.generate command should be non-empty")
}
// discovery field is optional as apps can now specify plugin names directly
return nil
diff --git a/cmpserver/plugin/config_test.go b/cmpserver/plugin/config_test.go
index 982e365c01..db08e92a2f 100644
--- a/cmpserver/plugin/config_test.go
+++ b/cmpserver/plugin/config_test.go
@@ -8,9 +8,9 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+ v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
- "github.com/argoproj/argo-cd/v3/common"
+ "github.com/argoproj/argo-cd/v2/common"
)
func Test_IsDefined(t *testing.T) {
@@ -88,7 +88,7 @@ func Test_ReadPluginConfig(t *testing.T) {
metadata:
`,
expected: nil,
- expectedErr: "invalid plugin configuration file. metadata.name should be non-empty",
+ expectedErr: "invalid plugin configuration file. metadata.name should be non-empty.",
},
{
name: "empty metadata name",
@@ -97,7 +97,7 @@ metadata:
name: ""
`,
expected: nil,
- expectedErr: "invalid plugin configuration file. metadata.name should be non-empty",
+ expectedErr: "invalid plugin configuration file. metadata.name should be non-empty.",
},
{
name: "invalid kind",
@@ -130,10 +130,10 @@ spec:
command: [command]
`,
expected: &PluginConfig{
- TypeMeta: metav1.TypeMeta{
+ TypeMeta: v1.TypeMeta{
Kind: ConfigManagementPluginKind,
},
- Metadata: metav1.ObjectMeta{
+ Metadata: v1.ObjectMeta{
Name: "name",
},
Spec: PluginConfigSpec{
@@ -177,10 +177,10 @@ func Test_PluginConfig_Address(t *testing.T) {
{
name: "no version specified",
config: &PluginConfig{
- TypeMeta: metav1.TypeMeta{
+ TypeMeta: v1.TypeMeta{
Kind: ConfigManagementPluginKind,
},
- Metadata: metav1.ObjectMeta{
+ Metadata: v1.ObjectMeta{
Name: "name",
},
},
@@ -189,10 +189,10 @@ func Test_PluginConfig_Address(t *testing.T) {
{
name: "version specified",
config: &PluginConfig{
- TypeMeta: metav1.TypeMeta{
+ TypeMeta: v1.TypeMeta{
Kind: ConfigManagementPluginKind,
},
- Metadata: metav1.ObjectMeta{
+ Metadata: v1.ObjectMeta{
Name: "name",
},
Spec: PluginConfigSpec{
diff --git a/cmpserver/plugin/plugin.go b/cmpserver/plugin/plugin.go
index d52a9ca3a7..c708edf9a0 100644
--- a/cmpserver/plugin/plugin.go
+++ b/cmpserver/plugin/plugin.go
@@ -3,8 +3,6 @@ package plugin
import (
"bytes"
"context"
- "crypto/rand"
- "encoding/hex"
"encoding/json"
"errors"
"fmt"
@@ -14,15 +12,16 @@ import (
"strings"
"time"
+ "github.com/argoproj/pkg/rand"
"github.com/golang/protobuf/ptypes/empty"
- "github.com/argoproj/argo-cd/v3/cmpserver/apiclient"
- "github.com/argoproj/argo-cd/v3/common"
- repoclient "github.com/argoproj/argo-cd/v3/reposerver/apiclient"
- "github.com/argoproj/argo-cd/v3/util/buffered_context"
- "github.com/argoproj/argo-cd/v3/util/cmp"
- argoexec "github.com/argoproj/argo-cd/v3/util/exec"
- "github.com/argoproj/argo-cd/v3/util/io/files"
+ "github.com/argoproj/argo-cd/v2/cmpserver/apiclient"
+ "github.com/argoproj/argo-cd/v2/common"
+ repoclient "github.com/argoproj/argo-cd/v2/reposerver/apiclient"
+ "github.com/argoproj/argo-cd/v2/util/buffered_context"
+ "github.com/argoproj/argo-cd/v2/util/cmp"
+ argoexec "github.com/argoproj/argo-cd/v2/util/exec"
+ "github.com/argoproj/argo-cd/v2/util/io/files"
"github.com/argoproj/gitops-engine/pkg/utils/kube"
securejoin "github.com/cyphar/filepath-securejoin"
@@ -62,26 +61,16 @@ func (s *Service) Init(workDir string) error {
return nil
}
-const execIDLen = 5
-
-func randExecID() (string, error) {
- execIDBytes := make([]byte, execIDLen/2+1) // we need one extra letter to discard
- if _, err := rand.Read(execIDBytes); err != nil {
- return "", err
- }
- return hex.EncodeToString(execIDBytes)[0:execIDLen], nil
-}
-
func runCommand(ctx context.Context, command Command, path string, env []string) (string, error) {
if len(command.Command) == 0 {
- return "", errors.New("Command is empty")
+ return "", fmt.Errorf("Command is empty")
}
cmd := exec.CommandContext(ctx, command.Command[0], append(command.Command[1:], command.Args...)...)
cmd.Env = env
cmd.Dir = path
- execId, err := randExecID()
+ execId, err := rand.RandString(5)
if err != nil {
return "", err
}
@@ -168,7 +157,7 @@ func newCmdError(args string, cause error, stderr string) *CmdError {
func environ(envVars []*apiclient.EnvEntry) []string {
var environ []string
for _, item := range envVars {
- if item != nil && item.Name != "" {
+ if item != nil && item.Name != "" && item.Value != "" {
environ = append(environ, fmt.Sprintf("%s=%s", item.Name, item.Value))
}
}
@@ -183,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]any{
+ log.WithFields(map[string]interface{}{
common.SecurityField: common.SecurityHigh,
common.SecurityCWEField: common.SecurityCWEIncompleteCleanup,
}).Errorf("Failed to clean up temp directory: %s", err)
@@ -223,7 +212,7 @@ func (s *Service) generateManifestGeneric(stream GenerateManifestStream) error {
appPath := filepath.Clean(filepath.Join(workDir, metadata.AppRelPath))
if !strings.HasPrefix(appPath, workDir) {
- return errors.New("illegal appPath: out of workDir bound")
+ return fmt.Errorf("illegal appPath: out of workDir bound")
}
response, err := s.generateManifest(ctx, appPath, metadata.GetEnv())
if err != nil {
@@ -326,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]any{
+ log.WithFields(map[string]interface{}{
common.SecurityField: common.SecurityHigh,
common.SecurityCWEField: common.SecurityCWEIncompleteCleanup,
}).Errorf("error joining workdir %q and appRelPath %q: %v", workdir, appRelPath, err)
@@ -395,7 +384,7 @@ func (s *Service) GetParametersAnnouncement(stream apiclient.ConfigManagementPlu
}
appPath := filepath.Clean(filepath.Join(workDir, metadata.AppRelPath))
if !strings.HasPrefix(appPath, workDir) {
- return errors.New("illegal appPath: out of workDir bound")
+ return fmt.Errorf("illegal appPath: out of workDir bound")
}
repoResponse, err := getParametersAnnouncement(bufferedCtx, appPath, s.initConstants.PluginConfig.Spec.Parameters.Static, s.initConstants.PluginConfig.Spec.Parameters.Dynamic, metadata.GetEnv())
@@ -436,7 +425,7 @@ func getParametersAnnouncement(ctx context.Context, appDir string, announcements
return repoResponse, nil
}
-func (s *Service) CheckPluginConfiguration(_ context.Context, _ *empty.Empty) (*apiclient.CheckPluginConfigurationResponse, error) {
+func (s *Service) CheckPluginConfiguration(ctx context.Context, _ *empty.Empty) (*apiclient.CheckPluginConfigurationResponse, error) {
isDiscoveryConfigured := s.isDiscoveryConfigured()
response := &apiclient.CheckPluginConfigurationResponse{IsDiscoveryConfigured: isDiscoveryConfigured, ProvideGitCreds: s.initConstants.PluginConfig.Spec.ProvideGitCreds}
diff --git a/cmpserver/plugin/plugin.proto b/cmpserver/plugin/plugin.proto
index 2b50785857..89fdd7418c 100644
--- a/cmpserver/plugin/plugin.proto
+++ b/cmpserver/plugin/plugin.proto
@@ -1,9 +1,9 @@
syntax = "proto3";
-option go_package = "github.com/argoproj/argo-cd/v3/cmpserver/apiclient";
+option go_package = "github.com/argoproj/argo-cd/v2/cmpserver/apiclient";
package plugin;
-import "github.com/argoproj/argo-cd/v3/reposerver/repository/repository.proto";
+import "github.com/argoproj/argo-cd/v2/reposerver/repository/repository.proto";
import "google/protobuf/empty.proto";
// AppStreamRequest is the request object used to send the application's
diff --git a/cmpserver/plugin/plugin_test.go b/cmpserver/plugin/plugin_test.go
index 3c6e436324..30bd0a97be 100644
--- a/cmpserver/plugin/plugin_test.go
+++ b/cmpserver/plugin/plugin_test.go
@@ -18,11 +18,11 @@ import (
"gopkg.in/yaml.v2"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
- "github.com/argoproj/argo-cd/v3/cmpserver/apiclient"
- repoclient "github.com/argoproj/argo-cd/v3/reposerver/apiclient"
- "github.com/argoproj/argo-cd/v3/test"
- "github.com/argoproj/argo-cd/v3/util/cmp"
- "github.com/argoproj/argo-cd/v3/util/tgzstream"
+ "github.com/argoproj/argo-cd/v2/cmpserver/apiclient"
+ repoclient "github.com/argoproj/argo-cd/v2/reposerver/apiclient"
+ "github.com/argoproj/argo-cd/v2/test"
+ "github.com/argoproj/argo-cd/v2/util/cmp"
+ "github.com/argoproj/argo-cd/v2/util/tgzstream"
)
func newService(configFilePath string) (*Service, error) {
@@ -100,7 +100,7 @@ func TestMatchRepository(t *testing.T) {
f := setup(t, withDiscover(d))
// when
- match, discovery, err := f.service.matchRepository(t.Context(), f.path, f.env, ".")
+ match, discovery, err := f.service.matchRepository(context.Background(), f.path, f.env, ".")
// then
require.NoError(t, err)
@@ -115,7 +115,7 @@ func TestMatchRepository(t *testing.T) {
f := setup(t, withDiscover(d))
// when
- match, discovery, err := f.service.matchRepository(t.Context(), f.path, f.env, ".")
+ match, discovery, err := f.service.matchRepository(context.Background(), f.path, f.env, ".")
// then
require.NoError(t, err)
@@ -130,7 +130,7 @@ func TestMatchRepository(t *testing.T) {
f := setup(t, withDiscover(d))
// when
- _, _, err := f.service.matchRepository(t.Context(), f.path, f.env, ".")
+ _, _, err := f.service.matchRepository(context.Background(), f.path, f.env, ".")
// then
require.ErrorContains(t, err, "syntax error")
@@ -145,7 +145,7 @@ func TestMatchRepository(t *testing.T) {
f := setup(t, withDiscover(d))
// when
- match, discovery, err := f.service.matchRepository(t.Context(), f.path, f.env, ".")
+ match, discovery, err := f.service.matchRepository(context.Background(), f.path, f.env, ".")
// then
require.NoError(t, err)
@@ -162,7 +162,7 @@ func TestMatchRepository(t *testing.T) {
f := setup(t, withDiscover(d))
// when
- match, discovery, err := f.service.matchRepository(t.Context(), f.path, f.env, ".")
+ match, discovery, err := f.service.matchRepository(context.Background(), f.path, f.env, ".")
// then
require.NoError(t, err)
@@ -179,7 +179,7 @@ func TestMatchRepository(t *testing.T) {
f := setup(t, withDiscover(d))
// when
- _, _, err := f.service.matchRepository(t.Context(), f.path, f.env, ".")
+ _, _, err := f.service.matchRepository(context.Background(), f.path, f.env, ".")
// then
require.ErrorContains(t, err, "error finding glob match for pattern")
@@ -196,7 +196,7 @@ func TestMatchRepository(t *testing.T) {
f := setup(t, withDiscover(d))
// when
- match, discovery, err := f.service.matchRepository(t.Context(), f.path, f.env, ".")
+ match, discovery, err := f.service.matchRepository(context.Background(), f.path, f.env, ".")
// then
require.NoError(t, err)
@@ -215,7 +215,7 @@ func TestMatchRepository(t *testing.T) {
f := setup(t, withDiscover(d))
// when
- match, discovery, err := f.service.matchRepository(t.Context(), f.path, f.env, ".")
+ match, discovery, err := f.service.matchRepository(context.Background(), f.path, f.env, ".")
// then
require.NoError(t, err)
assert.False(t, match)
@@ -233,7 +233,7 @@ func TestMatchRepository(t *testing.T) {
f := setup(t, withDiscover(d))
// when
- match, discovery, err := f.service.matchRepository(t.Context(), f.path, f.env, ".")
+ match, discovery, err := f.service.matchRepository(context.Background(), f.path, f.env, ".")
// then
require.NoError(t, err)
@@ -253,7 +253,7 @@ func TestMatchRepository(t *testing.T) {
f := setup(t, withDiscover(d))
// when
- match, discovery, err := f.service.matchRepository(t.Context(), f.path, f.env, ".")
+ match, discovery, err := f.service.matchRepository(context.Background(), f.path, f.env, ".")
// then
require.NoError(t, err)
@@ -272,7 +272,7 @@ func TestMatchRepository(t *testing.T) {
f := setup(t, withDiscover(d))
// when
- match, discovery, err := f.service.matchRepository(t.Context(), f.path, f.env, ".")
+ match, discovery, err := f.service.matchRepository(context.Background(), f.path, f.env, ".")
// then
require.Error(t, err)
@@ -285,7 +285,7 @@ func TestMatchRepository(t *testing.T) {
f := setup(t, withDiscover(d))
// when
- match, discovery, err := f.service.matchRepository(t.Context(), f.path, f.env, ".")
+ match, discovery, err := f.service.matchRepository(context.Background(), f.path, f.env, ".")
// then
require.NoError(t, err)
@@ -308,7 +308,7 @@ func TestGenerateManifest(t *testing.T) {
service, err := newService(configFilePath)
require.NoError(t, err)
- res1, err := service.generateManifest(t.Context(), "testdata/kustomize", nil)
+ res1, err := service.generateManifest(context.Background(), "testdata/kustomize", nil)
require.NoError(t, err)
require.NotNil(t, res1)
@@ -322,7 +322,7 @@ func TestGenerateManifest(t *testing.T) {
require.NoError(t, err)
service.WithGenerateCommand(Command{Command: []string{"bad-command"}})
- res, err := service.generateManifest(t.Context(), "testdata/kustomize", nil)
+ res, err := service.generateManifest(context.Background(), "testdata/kustomize", nil)
require.ErrorContains(t, err, "executable file not found")
assert.Nil(t, res.Manifests)
})
@@ -331,7 +331,7 @@ func TestGenerateManifest(t *testing.T) {
require.NoError(t, err)
service.WithGenerateCommand(Command{Command: []string{"echo", "invalid yaml: }"}})
- res, err := service.generateManifest(t.Context(), "testdata/kustomize", nil)
+ res, err := service.generateManifest(context.Background(), "testdata/kustomize", nil)
require.ErrorContains(t, err, "failed to unmarshal manifest")
assert.Nil(t, res.Manifests)
})
@@ -342,7 +342,7 @@ func TestGenerateManifest_deadline_exceeded(t *testing.T) {
service, err := newService(configFilePath)
require.NoError(t, err)
- expiredCtx, cancel := context.WithTimeout(t.Context(), time.Second*0)
+ expiredCtx, cancel := context.WithTimeout(context.Background(), time.Second*0)
defer cancel()
_, err = service.generateManifest(expiredCtx, "", nil)
require.ErrorContains(t, err, "context deadline exceeded")
@@ -350,7 +350,7 @@ func TestGenerateManifest_deadline_exceeded(t *testing.T) {
// TestRunCommandContextTimeout makes sure the command dies at timeout rather than sleeping past the timeout.
func TestRunCommandContextTimeout(t *testing.T) {
- ctx, cancel := context.WithTimeout(t.Context(), 990*time.Millisecond)
+ ctx, cancel := context.WithTimeout(context.Background(), 990*time.Millisecond)
defer cancel()
// Use a subshell so there's a child command.
command := Command{
@@ -365,13 +365,13 @@ func TestRunCommandContextTimeout(t *testing.T) {
}
func TestRunCommandEmptyCommand(t *testing.T) {
- _, err := runCommand(t.Context(), Command{}, "", nil)
+ _, err := runCommand(context.Background(), Command{}, "", nil)
require.ErrorContains(t, err, "Command is empty")
}
// TestRunCommandContextTimeoutWithCleanup makes sure that the process is given enough time to cleanup before sending SIGKILL.
func TestRunCommandContextTimeoutWithCleanup(t *testing.T) {
- ctx, cancel := context.WithTimeout(t.Context(), 900*time.Millisecond)
+ ctx, cancel := context.WithTimeout(context.Background(), 900*time.Millisecond)
defer cancel()
// Use a subshell so there's a child command.
@@ -403,7 +403,7 @@ func Test_getParametersAnnouncement_empty_command(t *testing.T) {
Command: []string{"echo"},
Args: []string{`[]`},
}
- res, err := getParametersAnnouncement(t.Context(), "", *static, command, []*apiclient.EnvEntry{})
+ res, err := getParametersAnnouncement(context.Background(), "", *static, command, []*apiclient.EnvEntry{})
require.NoError(t, err)
assert.Equal(t, []*repoclient.ParameterAnnouncement{{Name: "static-a"}, {Name: "static-b"}}, res.ParameterAnnouncements)
}
@@ -417,7 +417,7 @@ func Test_getParametersAnnouncement_no_command(t *testing.T) {
err := yaml.Unmarshal([]byte(staticYAML), static)
require.NoError(t, err)
command := Command{}
- res, err := getParametersAnnouncement(t.Context(), "", *static, command, []*apiclient.EnvEntry{})
+ res, err := getParametersAnnouncement(context.Background(), "", *static, command, []*apiclient.EnvEntry{})
require.NoError(t, err)
assert.Equal(t, []*repoclient.ParameterAnnouncement{{Name: "static-a"}, {Name: "static-b"}}, res.ParameterAnnouncements)
}
@@ -434,7 +434,7 @@ func Test_getParametersAnnouncement_static_and_dynamic(t *testing.T) {
Command: []string{"echo"},
Args: []string{`[{"name": "dynamic-a"}, {"name": "dynamic-b"}]`},
}
- res, err := getParametersAnnouncement(t.Context(), "", *static, command, []*apiclient.EnvEntry{})
+ res, err := getParametersAnnouncement(context.Background(), "", *static, command, []*apiclient.EnvEntry{})
require.NoError(t, err)
expected := []*repoclient.ParameterAnnouncement{
{Name: "dynamic-a"},
@@ -450,7 +450,7 @@ func Test_getParametersAnnouncement_invalid_json(t *testing.T) {
Command: []string{"echo"},
Args: []string{`[`},
}
- _, err := getParametersAnnouncement(t.Context(), "", []*repoclient.ParameterAnnouncement{}, command, []*apiclient.EnvEntry{})
+ _, err := getParametersAnnouncement(context.Background(), "", []*repoclient.ParameterAnnouncement{}, command, []*apiclient.EnvEntry{})
assert.ErrorContains(t, err, "unexpected end of JSON input")
}
@@ -459,7 +459,7 @@ func Test_getParametersAnnouncement_bad_command(t *testing.T) {
Command: []string{"exit"},
Args: []string{"1"},
}
- _, err := getParametersAnnouncement(t.Context(), "", []*repoclient.ParameterAnnouncement{}, command, []*apiclient.EnvEntry{})
+ _, err := getParametersAnnouncement(context.Background(), "", []*repoclient.ParameterAnnouncement{}, command, []*apiclient.EnvEntry{})
assert.ErrorContains(t, err, "error executing dynamic parameter output command")
}
@@ -514,20 +514,19 @@ func TestEnviron(t *testing.T) {
env := environ([]*apiclient.EnvEntry{})
assert.Nil(t, env)
})
- t.Run("env vars with empty names", func(t *testing.T) {
+ t.Run("env vars with empty names or values", func(t *testing.T) {
env := environ([]*apiclient.EnvEntry{
{Value: "test"},
{Name: "test"},
})
- assert.Equal(t, []string{"test="}, env)
+ assert.Nil(t, env)
})
t.Run("proper env vars", func(t *testing.T) {
env := environ([]*apiclient.EnvEntry{
{Name: "name1", Value: "value1"},
{Name: "name2", Value: "value2"},
- {Name: "name3", Value: ""},
})
- assert.Equal(t, []string{"name1=value1", "name2=value2", "name3="}, env)
+ assert.Equal(t, []string{"name1=value1", "name2=value2"}, env)
})
}
@@ -807,11 +806,11 @@ func (m *MockParametersAnnouncementStream) Context() context.Context {
return context.Background()
}
-func (m *MockParametersAnnouncementStream) SendMsg(any) error {
+func (m *MockParametersAnnouncementStream) SendMsg(interface{}) error {
return nil
}
-func (m *MockParametersAnnouncementStream) RecvMsg(any) error {
+func (m *MockParametersAnnouncementStream) RecvMsg(interface{}) error {
return nil
}
@@ -868,7 +867,7 @@ func TestService_CheckPluginConfiguration(t *testing.T) {
f := setup(t, withDiscover(d))
// when
- resp, err := f.service.CheckPluginConfiguration(t.Context(), &empty.Empty{})
+ resp, err := f.service.CheckPluginConfiguration(context.Background(), &empty.Empty{})
// then
require.NoError(t, err)
@@ -881,7 +880,7 @@ func TestService_CheckPluginConfiguration(t *testing.T) {
f := setup(t, withDiscover(d))
// when
- resp, err := f.service.CheckPluginConfiguration(t.Context(), &empty.Empty{})
+ resp, err := f.service.CheckPluginConfiguration(context.Background(), &empty.Empty{})
// then
require.NoError(t, err)
diff --git a/cmpserver/server.go b/cmpserver/server.go
index fbf6d93c1f..5d7eacd2fd 100644
--- a/cmpserver/server.go
+++ b/cmpserver/server.go
@@ -7,25 +7,26 @@ import (
"os/signal"
"syscall"
- grpc_prometheus "github.com/grpc-ecosystem/go-grpc-middleware/providers/prometheus"
- "github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/logging"
- "github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/recovery"
- "github.com/prometheus/client_golang/prometheus"
- log "github.com/sirupsen/logrus"
"go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
+
+ grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
+ grpc_logrus "github.com/grpc-ecosystem/go-grpc-middleware/logging/logrus"
+ grpc_prometheus "github.com/grpc-ecosystem/go-grpc-prometheus"
+ log "github.com/sirupsen/logrus"
"google.golang.org/grpc"
"google.golang.org/grpc/health"
"google.golang.org/grpc/health/grpc_health_v1"
- "google.golang.org/grpc/keepalive"
"google.golang.org/grpc/reflection"
- "github.com/argoproj/argo-cd/v3/cmpserver/apiclient"
- "github.com/argoproj/argo-cd/v3/cmpserver/plugin"
- "github.com/argoproj/argo-cd/v3/common"
- versionpkg "github.com/argoproj/argo-cd/v3/pkg/apiclient/version"
- "github.com/argoproj/argo-cd/v3/server/version"
- "github.com/argoproj/argo-cd/v3/util/errors"
- grpc_util "github.com/argoproj/argo-cd/v3/util/grpc"
+ "google.golang.org/grpc/keepalive"
+
+ "github.com/argoproj/argo-cd/v2/cmpserver/apiclient"
+ "github.com/argoproj/argo-cd/v2/cmpserver/plugin"
+ "github.com/argoproj/argo-cd/v2/common"
+ versionpkg "github.com/argoproj/argo-cd/v2/pkg/apiclient/version"
+ "github.com/argoproj/argo-cd/v2/server/version"
+ "github.com/argoproj/argo-cd/v2/util/errors"
+ grpc_util "github.com/argoproj/argo-cd/v2/util/grpc"
)
// ArgoCDCMPServer is the config management plugin server implementation
@@ -34,37 +35,33 @@ type ArgoCDCMPServer struct {
opts []grpc.ServerOption
initConstants plugin.CMPServerInitConstants
stopCh chan os.Signal
- doneCh chan any
+ doneCh chan interface{}
sig os.Signal
}
// NewServer returns a new instance of the Argo CD config management plugin server
func NewServer(initConstants plugin.CMPServerInitConstants) (*ArgoCDCMPServer, error) {
- var serverMetricsOptions []grpc_prometheus.ServerMetricsOption
if os.Getenv(common.EnvEnableGRPCTimeHistogramEnv) == "true" {
- serverMetricsOptions = append(serverMetricsOptions, grpc_prometheus.WithServerHandlingTimeHistogram())
+ grpc_prometheus.EnableHandlingTimeHistogram()
}
- serverMetrics := grpc_prometheus.NewServerMetrics(serverMetricsOptions...)
- reg := prometheus.NewRegistry()
- reg.MustRegister(serverMetrics)
serverLog := log.NewEntry(log.StandardLogger())
streamInterceptors := []grpc.StreamServerInterceptor{
otelgrpc.StreamServerInterceptor(), //nolint:staticcheck // TODO: ignore SA1019 for depreciation: see https://github.com/argoproj/argo-cd/issues/18258
- logging.StreamServerInterceptor(grpc_util.InterceptorLogger(serverLog)),
- serverMetrics.StreamServerInterceptor(),
- recovery.StreamServerInterceptor(recovery.WithRecoveryHandler(grpc_util.LoggerRecoveryHandler(serverLog))),
+ grpc_logrus.StreamServerInterceptor(serverLog),
+ grpc_prometheus.StreamServerInterceptor,
+ grpc_util.PanicLoggerStreamServerInterceptor(serverLog),
}
unaryInterceptors := []grpc.UnaryServerInterceptor{
otelgrpc.UnaryServerInterceptor(), //nolint:staticcheck // TODO: ignore SA1019 for depreciation: see https://github.com/argoproj/argo-cd/issues/18258
- logging.UnaryServerInterceptor(grpc_util.InterceptorLogger(serverLog)),
- serverMetrics.UnaryServerInterceptor(),
- recovery.UnaryServerInterceptor(recovery.WithRecoveryHandler(grpc_util.LoggerRecoveryHandler(serverLog))),
+ grpc_logrus.UnaryServerInterceptor(serverLog),
+ grpc_prometheus.UnaryServerInterceptor,
+ grpc_util.PanicLoggerUnaryServerInterceptor(serverLog),
}
serverOpts := []grpc.ServerOption{
- grpc.ChainUnaryInterceptor(unaryInterceptors...),
- grpc.ChainStreamInterceptor(streamInterceptors...),
+ grpc.UnaryInterceptor(grpc_middleware.ChainUnaryServer(unaryInterceptors...)),
+ grpc.StreamInterceptor(grpc_middleware.ChainStreamServer(streamInterceptors...)),
grpc.MaxRecvMsgSize(apiclient.MaxGRPCMessageSize),
grpc.MaxSendMsgSize(apiclient.MaxGRPCMessageSize),
grpc.KeepaliveEnforcementPolicy(
@@ -78,7 +75,7 @@ func NewServer(initConstants plugin.CMPServerInitConstants) (*ArgoCDCMPServer, e
log: serverLog,
opts: serverOpts,
stopCh: make(chan os.Signal),
- doneCh: make(chan any),
+ doneCh: make(chan interface{}),
initConstants: initConstants,
}, nil
}
diff --git a/commitserver/apiclient/clientset.go b/commitserver/apiclient/clientset.go
index 0726c86434..795766e54e 100644
--- a/commitserver/apiclient/clientset.go
+++ b/commitserver/apiclient/clientset.go
@@ -7,12 +7,12 @@ import (
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
- utilio "github.com/argoproj/argo-cd/v3/util/io"
+ "github.com/argoproj/argo-cd/v2/util/io"
)
// Clientset represents commit server api clients
type Clientset interface {
- NewCommitServerClient() (utilio.Closer, CommitServiceClient, error)
+ NewCommitServerClient() (io.Closer, CommitServiceClient, error)
}
type clientSet struct {
@@ -20,7 +20,7 @@ type clientSet struct {
}
// NewCommitServerClient creates new instance of commit server client
-func (c *clientSet) NewCommitServerClient() (utilio.Closer, CommitServiceClient, error) {
+func (c *clientSet) NewCommitServerClient() (io.Closer, CommitServiceClient, error) {
conn, err := NewConnection(c.address)
if err != nil {
return nil, nil, fmt.Errorf("failed to open a new connection to commit server: %w", err)
@@ -34,7 +34,7 @@ func NewConnection(address string) (*grpc.ClientConn, error) {
opts = append(opts, grpc.WithTransportCredentials(insecure.NewCredentials()))
// TODO: switch to grpc.NewClient.
- //nolint:staticcheck
+ // nolint:staticcheck
conn, err := grpc.Dial(address, opts...)
if err != nil {
log.Errorf("Unable to connect to commit service with address %s", address)
diff --git a/commitserver/apiclient/commit.pb.go b/commitserver/apiclient/commit.pb.go
index 8a6cd85e71..3e37157582 100644
--- a/commitserver/apiclient/commit.pb.go
+++ b/commitserver/apiclient/commit.pb.go
@@ -6,7 +6,7 @@ package apiclient
import (
context "context"
fmt "fmt"
- v1alpha1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ v1alpha1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
proto "github.com/gogo/protobuf/proto"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
@@ -301,32 +301,32 @@ var fileDescriptor_cf3a3abbc35e3069 = []byte{
// 446 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x84, 0x93, 0xc1, 0x6e, 0xd3, 0x40,
0x10, 0x86, 0xe5, 0x24, 0x8d, 0xc8, 0xa4, 0xbd, 0xec, 0x81, 0x5a, 0x39, 0xb8, 0x96, 0xc5, 0x21,
- 0x17, 0xd6, 0x6a, 0x22, 0xb8, 0x71, 0x69, 0x38, 0x54, 0x88, 0x02, 0x72, 0x6e, 0xa8, 0x12, 0xda,
- 0xae, 0x07, 0x7b, 0x69, 0xec, 0x5d, 0x76, 0x37, 0x96, 0xf2, 0x3e, 0x3c, 0x0c, 0x47, 0x1e, 0x01,
- 0xe5, 0x49, 0x90, 0xd7, 0x36, 0x8d, 0x91, 0x42, 0x4e, 0x9e, 0xf9, 0x67, 0xf4, 0xcd, 0xe8, 0xf7,
- 0x2c, 0x84, 0x5c, 0x16, 0x85, 0xb0, 0x06, 0x75, 0x85, 0x3a, 0x6e, 0x92, 0xf6, 0x43, 0x95, 0x96,
- 0x56, 0xce, 0xde, 0x67, 0xc2, 0xe6, 0xdb, 0x07, 0xca, 0x65, 0x11, 0x33, 0x9d, 0x49, 0xa5, 0xe5,
- 0x37, 0x17, 0xbc, 0xe4, 0x69, 0x5c, 0x2d, 0x63, 0xf5, 0x98, 0xc5, 0x4c, 0x09, 0x13, 0x33, 0xa5,
- 0x36, 0x82, 0x33, 0x2b, 0x64, 0x19, 0x57, 0xd7, 0x6c, 0xa3, 0x72, 0x76, 0x1d, 0x67, 0x58, 0xa2,
- 0x66, 0x16, 0xd3, 0x86, 0x16, 0xfd, 0x18, 0x40, 0xb0, 0x72, 0xf8, 0xdb, 0x5d, 0xea, 0x0a, 0x77,
- 0xac, 0x14, 0x5f, 0xd1, 0x58, 0x93, 0xe0, 0xf7, 0x2d, 0x1a, 0x4b, 0xee, 0x61, 0xa4, 0x51, 0x49,
- 0xdf, 0x0b, 0xbd, 0xf9, 0x74, 0x71, 0x4b, 0x9f, 0xe6, 0xd3, 0x6e, 0xbe, 0x0b, 0xbe, 0xf0, 0x94,
- 0x56, 0x4b, 0xaa, 0x1e, 0x33, 0x5a, 0xcf, 0xa7, 0x07, 0xf3, 0x69, 0x37, 0x9f, 0x26, 0xa8, 0xa4,
- 0x11, 0x56, 0xea, 0x5d, 0xe2, 0xa8, 0x24, 0x00, 0x30, 0xbb, 0x92, 0xdf, 0x68, 0x56, 0xf2, 0xdc,
- 0x1f, 0x84, 0xde, 0x7c, 0x92, 0x1c, 0x28, 0x24, 0x82, 0x73, 0xcb, 0x74, 0x86, 0xb6, 0xed, 0x18,
- 0xba, 0x8e, 0x9e, 0x46, 0x9e, 0xc3, 0x38, 0xd5, 0xbb, 0x75, 0xce, 0xfc, 0x91, 0xab, 0xb6, 0x19,
- 0x79, 0x01, 0x17, 0x8d, 0x75, 0x77, 0x68, 0x0c, 0xcb, 0xd0, 0x3f, 0x73, 0xe5, 0xbe, 0x48, 0x22,
- 0x38, 0x53, 0xcc, 0xe6, 0xc6, 0x1f, 0x87, 0xc3, 0xf9, 0x74, 0x71, 0x4e, 0x3f, 0x31, 0x9b, 0xbf,
- 0x45, 0xcb, 0xc4, 0xc6, 0x24, 0x4d, 0x29, 0xda, 0xc2, 0xf4, 0x40, 0x25, 0x04, 0x46, 0xb5, 0xee,
- 0x2c, 0x99, 0x24, 0x2e, 0x26, 0xaf, 0x61, 0x52, 0x74, 0xd6, 0xf9, 0x03, 0x87, 0xf2, 0xe9, 0xbf,
- 0xa6, 0x76, 0xd8, 0xa7, 0x56, 0x32, 0x83, 0x67, 0xf5, 0x3e, 0xac, 0x4c, 0x8d, 0x3f, 0x0c, 0x87,
- 0xf3, 0x49, 0xf2, 0x37, 0x8f, 0xde, 0xc0, 0xe5, 0x11, 0x42, 0xed, 0x4b, 0xc7, 0x78, 0xb7, 0xfe,
- 0xf8, 0xa1, 0x5d, 0xa5, 0xa7, 0x45, 0x2b, 0xb8, 0x3a, 0xfa, 0x6f, 0x8d, 0x92, 0xa5, 0x41, 0x12,
- 0xc2, 0x34, 0x6f, 0x8b, 0xb5, 0x7f, 0x0d, 0xe5, 0x50, 0x5a, 0x14, 0x70, 0xd1, 0x40, 0xd6, 0xa8,
- 0x2b, 0xc1, 0x91, 0xdc, 0xc3, 0xe5, 0x11, 0x2a, 0xb9, 0xa2, 0xff, 0xbf, 0xa5, 0x59, 0x48, 0x4f,
- 0x2c, 0x74, 0xb3, 0xfa, 0xb9, 0x0f, 0xbc, 0x5f, 0xfb, 0xc0, 0xfb, 0xbd, 0x0f, 0xbc, 0xcf, 0xaf,
- 0x4e, 0x1c, 0x7b, 0xef, 0xb5, 0x30, 0x25, 0xf8, 0x46, 0x60, 0x69, 0x1f, 0xc6, 0xee, 0xb8, 0x97,
- 0x7f, 0x02, 0x00, 0x00, 0xff, 0xff, 0xf1, 0x83, 0xe8, 0xd7, 0x4e, 0x03, 0x00, 0x00,
+ 0x17, 0xd6, 0xaa, 0x11, 0xdc, 0xb8, 0x34, 0x1c, 0x2a, 0x44, 0x01, 0x39, 0x37, 0x54, 0x09, 0x6d,
+ 0xd7, 0x83, 0xbd, 0x34, 0xf6, 0x2e, 0xbb, 0x1b, 0x4b, 0x79, 0x1f, 0x1e, 0x86, 0x23, 0x8f, 0x80,
+ 0xf2, 0x24, 0xc8, 0x6b, 0x9b, 0xc6, 0x48, 0x69, 0x4f, 0x9e, 0xf9, 0x67, 0xf4, 0xcd, 0xe8, 0xf7,
+ 0x2c, 0x84, 0x5c, 0x96, 0xa5, 0xb0, 0x06, 0x75, 0x8d, 0x3a, 0x6e, 0x93, 0xee, 0x43, 0x95, 0x96,
+ 0x56, 0x2e, 0x3e, 0xe4, 0xc2, 0x16, 0xdb, 0x3b, 0xca, 0x65, 0x19, 0x33, 0x9d, 0x4b, 0xa5, 0xe5,
+ 0x77, 0x17, 0xbc, 0xe4, 0x59, 0x5c, 0x27, 0xb1, 0xba, 0xcf, 0x63, 0xa6, 0x84, 0x89, 0x99, 0x52,
+ 0x1b, 0xc1, 0x99, 0x15, 0xb2, 0x8a, 0xeb, 0x4b, 0xb6, 0x51, 0x05, 0xbb, 0x8c, 0x73, 0xac, 0x50,
+ 0x33, 0x8b, 0x59, 0x4b, 0x8b, 0x7e, 0x8e, 0x20, 0x58, 0x39, 0xfc, 0xf5, 0x2e, 0x73, 0x85, 0x1b,
+ 0x56, 0x89, 0x6f, 0x68, 0xac, 0x49, 0xf1, 0xc7, 0x16, 0x8d, 0x25, 0xb7, 0x30, 0xd1, 0xa8, 0xa4,
+ 0xef, 0x85, 0xde, 0x72, 0x9e, 0x5c, 0xd3, 0x87, 0xf9, 0xb4, 0x9f, 0xef, 0x82, 0xaf, 0x3c, 0xa3,
+ 0x75, 0x42, 0xd5, 0x7d, 0x4e, 0x9b, 0xf9, 0xf4, 0x60, 0x3e, 0xed, 0xe7, 0xd3, 0x14, 0x95, 0x34,
+ 0xc2, 0x4a, 0xbd, 0x4b, 0x1d, 0x95, 0x04, 0x00, 0x66, 0x57, 0xf1, 0x2b, 0xcd, 0x2a, 0x5e, 0xf8,
+ 0xa3, 0xd0, 0x5b, 0xce, 0xd2, 0x03, 0x85, 0x44, 0x70, 0x6a, 0x99, 0xce, 0xd1, 0x76, 0x1d, 0x63,
+ 0xd7, 0x31, 0xd0, 0xc8, 0x73, 0x98, 0x66, 0x7a, 0xb7, 0x2e, 0x98, 0x3f, 0x71, 0xd5, 0x2e, 0x23,
+ 0x2f, 0xe0, 0xac, 0xb5, 0xee, 0x06, 0x8d, 0x61, 0x39, 0xfa, 0x27, 0xae, 0x3c, 0x14, 0x49, 0x04,
+ 0x27, 0x8a, 0xd9, 0xc2, 0xf8, 0xd3, 0x70, 0xbc, 0x9c, 0x27, 0xa7, 0xf4, 0x33, 0xb3, 0xc5, 0x3b,
+ 0xb4, 0x4c, 0x6c, 0x4c, 0xda, 0x96, 0xa2, 0x2d, 0xcc, 0x0f, 0x54, 0x42, 0x60, 0xd2, 0xe8, 0xce,
+ 0x92, 0x59, 0xea, 0x62, 0xf2, 0x06, 0x66, 0x65, 0x6f, 0x9d, 0x3f, 0x72, 0x28, 0x9f, 0xfe, 0x6f,
+ 0x6a, 0x8f, 0x7d, 0x68, 0x25, 0x0b, 0x78, 0xd6, 0xec, 0xc3, 0xaa, 0xcc, 0xf8, 0xe3, 0x70, 0xbc,
+ 0x9c, 0xa5, 0xff, 0xf2, 0xe8, 0x2d, 0x9c, 0x1f, 0x21, 0x34, 0xbe, 0xf4, 0x8c, 0xf7, 0xeb, 0x4f,
+ 0x1f, 0xbb, 0x55, 0x06, 0x5a, 0xb4, 0x82, 0x8b, 0xa3, 0xff, 0xd6, 0x28, 0x59, 0x19, 0x24, 0x21,
+ 0xcc, 0x8b, 0xae, 0xd8, 0xf8, 0xd7, 0x52, 0x0e, 0xa5, 0xa4, 0x84, 0xb3, 0x16, 0xb2, 0x46, 0x5d,
+ 0x0b, 0x8e, 0xe4, 0x16, 0xce, 0x8f, 0x50, 0xc9, 0x05, 0x7d, 0xfc, 0x96, 0x16, 0x21, 0x7d, 0x62,
+ 0xa1, 0xab, 0xd5, 0xaf, 0x7d, 0xe0, 0xfd, 0xde, 0x07, 0xde, 0x9f, 0x7d, 0xe0, 0x7d, 0x79, 0xfd,
+ 0xc4, 0xb1, 0x0f, 0x5e, 0x0b, 0x53, 0x82, 0x6f, 0x04, 0x56, 0xf6, 0x6e, 0xea, 0x8e, 0xfb, 0xd5,
+ 0xdf, 0x00, 0x00, 0x00, 0xff, 0xff, 0x89, 0xb8, 0xdf, 0x48, 0x4e, 0x03, 0x00, 0x00,
}
// Reference imports to suppress errors if they are not otherwise used.
diff --git a/commitserver/apiclient/mocks/Clientset.go b/commitserver/apiclient/mocks/Clientset.go
index 4e156f6e7e..7ec0166f66 100644
--- a/commitserver/apiclient/mocks/Clientset.go
+++ b/commitserver/apiclient/mocks/Clientset.go
@@ -1,15 +1,58 @@
-// Code generated by mockery; DO NOT EDIT.
-// github.com/vektra/mockery
-// template: testify
+// Code generated by mockery v2.53.4. DO NOT EDIT.
package mocks
import (
- "github.com/argoproj/argo-cd/v3/commitserver/apiclient"
- "github.com/argoproj/argo-cd/v3/util/io"
+ apiclient "github.com/argoproj/argo-cd/v2/commitserver/apiclient"
+ io "github.com/argoproj/argo-cd/v2/util/io"
+
mock "github.com/stretchr/testify/mock"
)
+// Clientset is an autogenerated mock type for the Clientset type
+type Clientset struct {
+ mock.Mock
+}
+
+// NewCommitServerClient provides a mock function with no fields
+func (_m *Clientset) NewCommitServerClient() (io.Closer, apiclient.CommitServiceClient, error) {
+ ret := _m.Called()
+
+ if len(ret) == 0 {
+ panic("no return value specified for NewCommitServerClient")
+ }
+
+ var r0 io.Closer
+ var r1 apiclient.CommitServiceClient
+ var r2 error
+ if rf, ok := ret.Get(0).(func() (io.Closer, apiclient.CommitServiceClient, error)); ok {
+ return rf()
+ }
+ if rf, ok := ret.Get(0).(func() io.Closer); ok {
+ r0 = rf()
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(io.Closer)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func() apiclient.CommitServiceClient); ok {
+ r1 = rf()
+ } else {
+ if ret.Get(1) != nil {
+ r1 = ret.Get(1).(apiclient.CommitServiceClient)
+ }
+ }
+
+ if rf, ok := ret.Get(2).(func() error); ok {
+ r2 = rf()
+ } else {
+ r2 = ret.Error(2)
+ }
+
+ return r0, r1, r2
+}
+
// NewClientset creates a new instance of Clientset. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
// The first argument is typically a *testing.T value.
func NewClientset(t interface {
@@ -23,79 +66,3 @@ func NewClientset(t interface {
return mock
}
-
-// Clientset is an autogenerated mock type for the Clientset type
-type Clientset struct {
- mock.Mock
-}
-
-type Clientset_Expecter struct {
- mock *mock.Mock
-}
-
-func (_m *Clientset) EXPECT() *Clientset_Expecter {
- return &Clientset_Expecter{mock: &_m.Mock}
-}
-
-// NewCommitServerClient provides a mock function for the type Clientset
-func (_mock *Clientset) NewCommitServerClient() (io.Closer, apiclient.CommitServiceClient, error) {
- ret := _mock.Called()
-
- if len(ret) == 0 {
- panic("no return value specified for NewCommitServerClient")
- }
-
- var r0 io.Closer
- var r1 apiclient.CommitServiceClient
- var r2 error
- if returnFunc, ok := ret.Get(0).(func() (io.Closer, apiclient.CommitServiceClient, error)); ok {
- return returnFunc()
- }
- if returnFunc, ok := ret.Get(0).(func() io.Closer); ok {
- r0 = returnFunc()
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(io.Closer)
- }
- }
- if returnFunc, ok := ret.Get(1).(func() apiclient.CommitServiceClient); ok {
- r1 = returnFunc()
- } else {
- if ret.Get(1) != nil {
- r1 = ret.Get(1).(apiclient.CommitServiceClient)
- }
- }
- if returnFunc, ok := ret.Get(2).(func() error); ok {
- r2 = returnFunc()
- } else {
- r2 = ret.Error(2)
- }
- return r0, r1, r2
-}
-
-// Clientset_NewCommitServerClient_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'NewCommitServerClient'
-type Clientset_NewCommitServerClient_Call struct {
- *mock.Call
-}
-
-// NewCommitServerClient is a helper method to define mock.On call
-func (_e *Clientset_Expecter) NewCommitServerClient() *Clientset_NewCommitServerClient_Call {
- return &Clientset_NewCommitServerClient_Call{Call: _e.mock.On("NewCommitServerClient")}
-}
-
-func (_c *Clientset_NewCommitServerClient_Call) Run(run func()) *Clientset_NewCommitServerClient_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run()
- })
- return _c
-}
-
-func (_c *Clientset_NewCommitServerClient_Call) Return(closer io.Closer, commitServiceClient apiclient.CommitServiceClient, err error) *Clientset_NewCommitServerClient_Call {
- _c.Call.Return(closer, commitServiceClient, err)
- return _c
-}
-
-func (_c *Clientset_NewCommitServerClient_Call) RunAndReturn(run func() (io.Closer, apiclient.CommitServiceClient, error)) *Clientset_NewCommitServerClient_Call {
- _c.Call.Return(run)
- return _c
-}
diff --git a/commitserver/apiclient/mocks/CommitServiceClient.go b/commitserver/apiclient/mocks/CommitServiceClient.go
index 03588692ea..3119edf3cd 100644
--- a/commitserver/apiclient/mocks/CommitServiceClient.go
+++ b/commitserver/apiclient/mocks/CommitServiceClient.go
@@ -1,17 +1,59 @@
-// Code generated by mockery; DO NOT EDIT.
-// github.com/vektra/mockery
-// template: testify
+// Code generated by mockery v2.53.4. DO NOT EDIT.
package mocks
import (
- "context"
+ context "context"
+
+ apiclient "github.com/argoproj/argo-cd/v2/commitserver/apiclient"
+
+ grpc "google.golang.org/grpc"
- "github.com/argoproj/argo-cd/v3/commitserver/apiclient"
mock "github.com/stretchr/testify/mock"
- "google.golang.org/grpc"
)
+// CommitServiceClient is an autogenerated mock type for the CommitServiceClient type
+type CommitServiceClient struct {
+ mock.Mock
+}
+
+// CommitHydratedManifests provides a mock function with given fields: ctx, in, opts
+func (_m *CommitServiceClient) CommitHydratedManifests(ctx context.Context, in *apiclient.CommitHydratedManifestsRequest, opts ...grpc.CallOption) (*apiclient.CommitHydratedManifestsResponse, error) {
+ _va := make([]interface{}, len(opts))
+ for _i := range opts {
+ _va[_i] = opts[_i]
+ }
+ var _ca []interface{}
+ _ca = append(_ca, ctx, in)
+ _ca = append(_ca, _va...)
+ ret := _m.Called(_ca...)
+
+ if len(ret) == 0 {
+ panic("no return value specified for CommitHydratedManifests")
+ }
+
+ var r0 *apiclient.CommitHydratedManifestsResponse
+ var r1 error
+ if rf, ok := ret.Get(0).(func(context.Context, *apiclient.CommitHydratedManifestsRequest, ...grpc.CallOption) (*apiclient.CommitHydratedManifestsResponse, error)); ok {
+ return rf(ctx, in, opts...)
+ }
+ if rf, ok := ret.Get(0).(func(context.Context, *apiclient.CommitHydratedManifestsRequest, ...grpc.CallOption) *apiclient.CommitHydratedManifestsResponse); ok {
+ r0 = rf(ctx, in, opts...)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(*apiclient.CommitHydratedManifestsResponse)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(context.Context, *apiclient.CommitHydratedManifestsRequest, ...grpc.CallOption) error); ok {
+ r1 = rf(ctx, in, opts...)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
// NewCommitServiceClient creates a new instance of CommitServiceClient. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
// The first argument is typically a *testing.T value.
func NewCommitServiceClient(t interface {
@@ -25,89 +67,3 @@ func NewCommitServiceClient(t interface {
return mock
}
-
-// CommitServiceClient is an autogenerated mock type for the CommitServiceClient type
-type CommitServiceClient struct {
- mock.Mock
-}
-
-type CommitServiceClient_Expecter struct {
- mock *mock.Mock
-}
-
-func (_m *CommitServiceClient) EXPECT() *CommitServiceClient_Expecter {
- return &CommitServiceClient_Expecter{mock: &_m.Mock}
-}
-
-// CommitHydratedManifests provides a mock function for the type CommitServiceClient
-func (_mock *CommitServiceClient) CommitHydratedManifests(ctx context.Context, in *apiclient.CommitHydratedManifestsRequest, opts ...grpc.CallOption) (*apiclient.CommitHydratedManifestsResponse, error) {
- // grpc.CallOption
- _va := make([]interface{}, len(opts))
- for _i := range opts {
- _va[_i] = opts[_i]
- }
- var _ca []interface{}
- _ca = append(_ca, ctx, in)
- _ca = append(_ca, _va...)
- ret := _mock.Called(_ca...)
-
- if len(ret) == 0 {
- panic("no return value specified for CommitHydratedManifests")
- }
-
- var r0 *apiclient.CommitHydratedManifestsResponse
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(context.Context, *apiclient.CommitHydratedManifestsRequest, ...grpc.CallOption) (*apiclient.CommitHydratedManifestsResponse, error)); ok {
- return returnFunc(ctx, in, opts...)
- }
- if returnFunc, ok := ret.Get(0).(func(context.Context, *apiclient.CommitHydratedManifestsRequest, ...grpc.CallOption) *apiclient.CommitHydratedManifestsResponse); ok {
- r0 = returnFunc(ctx, in, opts...)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(*apiclient.CommitHydratedManifestsResponse)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(context.Context, *apiclient.CommitHydratedManifestsRequest, ...grpc.CallOption) error); ok {
- r1 = returnFunc(ctx, in, opts...)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// CommitServiceClient_CommitHydratedManifests_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CommitHydratedManifests'
-type CommitServiceClient_CommitHydratedManifests_Call struct {
- *mock.Call
-}
-
-// CommitHydratedManifests is a helper method to define mock.On call
-// - ctx
-// - in
-// - opts
-func (_e *CommitServiceClient_Expecter) CommitHydratedManifests(ctx interface{}, in interface{}, opts ...interface{}) *CommitServiceClient_CommitHydratedManifests_Call {
- return &CommitServiceClient_CommitHydratedManifests_Call{Call: _e.mock.On("CommitHydratedManifests",
- append([]interface{}{ctx, in}, opts...)...)}
-}
-
-func (_c *CommitServiceClient_CommitHydratedManifests_Call) Run(run func(ctx context.Context, in *apiclient.CommitHydratedManifestsRequest, opts ...grpc.CallOption)) *CommitServiceClient_CommitHydratedManifests_Call {
- _c.Call.Run(func(args mock.Arguments) {
- variadicArgs := make([]grpc.CallOption, len(args)-2)
- for i, a := range args[2:] {
- if a != nil {
- variadicArgs[i] = a.(grpc.CallOption)
- }
- }
- run(args[0].(context.Context), args[1].(*apiclient.CommitHydratedManifestsRequest), variadicArgs...)
- })
- return _c
-}
-
-func (_c *CommitServiceClient_CommitHydratedManifests_Call) Return(commitHydratedManifestsResponse *apiclient.CommitHydratedManifestsResponse, err error) *CommitServiceClient_CommitHydratedManifests_Call {
- _c.Call.Return(commitHydratedManifestsResponse, err)
- return _c
-}
-
-func (_c *CommitServiceClient_CommitHydratedManifests_Call) RunAndReturn(run func(ctx context.Context, in *apiclient.CommitHydratedManifestsRequest, opts ...grpc.CallOption) (*apiclient.CommitHydratedManifestsResponse, error)) *CommitServiceClient_CommitHydratedManifests_Call {
- _c.Call.Return(run)
- return _c
-}
diff --git a/commitserver/commit/commit.go b/commitserver/commit/commit.go
index b752ad509b..0a40b3a7d6 100644
--- a/commitserver/commit/commit.go
+++ b/commitserver/commit/commit.go
@@ -2,17 +2,16 @@ package commit
import (
"context"
- "errors"
"fmt"
"os"
"time"
log "github.com/sirupsen/logrus"
- "github.com/argoproj/argo-cd/v3/commitserver/apiclient"
- "github.com/argoproj/argo-cd/v3/commitserver/metrics"
- "github.com/argoproj/argo-cd/v3/util/git"
- "github.com/argoproj/argo-cd/v3/util/io/files"
+ "github.com/argoproj/argo-cd/v2/commitserver/apiclient"
+ "github.com/argoproj/argo-cd/v2/commitserver/metrics"
+ "github.com/argoproj/argo-cd/v2/util/git"
+ "github.com/argoproj/argo-cd/v2/util/io/files"
)
// Service is the service that handles commit requests.
@@ -34,7 +33,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(_ context.Context, r *apiclient.CommitHydratedManifestsRequest) (*apiclient.CommitHydratedManifestsResponse, error) {
+func (s *Service) CommitHydratedManifests(ctx 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()
@@ -79,16 +78,16 @@ func (s *Service) CommitHydratedManifests(_ context.Context, r *apiclient.Commit
// the changes. It returns the output of the git commands and an error if one occurred.
func (s *Service) handleCommitRequest(logCtx *log.Entry, r *apiclient.CommitHydratedManifestsRequest) (string, string, error) {
if r.Repo == nil {
- return "", "", errors.New("repo is required")
+ return "", "", fmt.Errorf("repo is required")
}
if r.Repo.Repo == "" {
- return "", "", errors.New("repo URL is required")
+ return "", "", fmt.Errorf("repo URL is required")
}
if r.TargetBranch == "" {
- return "", "", errors.New("target branch is required")
+ return "", "", fmt.Errorf("target branch is required")
}
if r.SyncBranch == "" {
- return "", "", errors.New("sync branch is required")
+ return "", "", fmt.Errorf("sync branch is required")
}
logCtx = logCtx.WithField("repo", r.Repo.Repo)
@@ -176,15 +175,15 @@ func (s *Service) initGitClient(logCtx *log.Entry, r *apiclient.CommitHydratedMa
}
// FIXME: make it work for GHE
- // logCtx.Debugf("Getting user info for repo credentials")
- // gitCreds := r.Repo.GetGitCreds(s.gitCredsStore)
- // startTime := time.Now()
- // authorName, authorEmail, err := gitCreds.GetUserInfo(ctx)
- // s.metricsServer.ObserveUserInfoRequestDuration(r.Repo.Repo, getCredentialType(r.Repo), time.Since(startTime))
- // if err != nil {
- // cleanupOrLog()
- // return nil, "", nil, fmt.Errorf("failed to get github app info: %w", err)
- // }
+ //logCtx.Debugf("Getting user info for repo credentials")
+ //gitCreds := r.Repo.GetGitCreds(s.gitCredsStore)
+ //startTime := time.Now()
+ //authorName, authorEmail, err := gitCreds.GetUserInfo(ctx)
+ //s.metricsServer.ObserveUserInfoRequestDuration(r.Repo.Repo, getCredentialType(r.Repo), time.Since(startTime))
+ //if err != nil {
+ // cleanupOrLog()
+ // return nil, "", nil, fmt.Errorf("failed to get github app info: %w", err)
+ //}
var authorName, authorEmail string
if authorName == "" {
diff --git a/commitserver/commit/commit.proto b/commitserver/commit/commit.proto
index a6eda97ed6..fdf8b23c0d 100644
--- a/commitserver/commit/commit.proto
+++ b/commitserver/commit/commit.proto
@@ -1,13 +1,13 @@
syntax = "proto3";
-option go_package = "github.com/argoproj/argo-cd/v3/commitserver/apiclient";
+option go_package = "github.com/argoproj/argo-cd/v2/commitserver/apiclient";
-import "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1/generated.proto";
+import "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1/generated.proto";
// CommitHydratedManifestsRequest is the request to commit hydrated manifests to a repository.
message CommitHydratedManifestsRequest {
// Repo contains repository information including, at minimum, the URL of the repository. Generally it will contain
// repo credentials.
- github.com.argoproj.argo_cd.v3.pkg.apis.application.v1alpha1.Repository repo = 1;
+ github.com.argoproj.argo_cd.v2.pkg.apis.application.v1alpha1.Repository repo = 1;
// SyncBranch is the branch Argo CD syncs from, i.e. the hydrated branch.
string syncBranch = 2;
// TargetBranch is the branch Argo CD is committing to, i.e. the branch that will be updated.
diff --git a/commitserver/commit/commit_test.go b/commitserver/commit/commit_test.go
index 547561a906..77bb9b5348 100644
--- a/commitserver/commit/commit_test.go
+++ b/commitserver/commit/commit_test.go
@@ -1,18 +1,19 @@
package commit
import (
+ "context"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
- "github.com/argoproj/argo-cd/v3/commitserver/apiclient"
- "github.com/argoproj/argo-cd/v3/commitserver/commit/mocks"
- "github.com/argoproj/argo-cd/v3/commitserver/metrics"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- "github.com/argoproj/argo-cd/v3/util/git"
- gitmocks "github.com/argoproj/argo-cd/v3/util/git/mocks"
+ "github.com/argoproj/argo-cd/v2/commitserver/apiclient"
+ "github.com/argoproj/argo-cd/v2/commitserver/commit/mocks"
+ "github.com/argoproj/argo-cd/v2/commitserver/metrics"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/util/git"
+ gitmocks "github.com/argoproj/argo-cd/v2/util/git/mocks"
)
func Test_CommitHydratedManifests(t *testing.T) {
@@ -32,7 +33,7 @@ func Test_CommitHydratedManifests(t *testing.T) {
service, _ := newServiceWithMocks(t)
request := &apiclient.CommitHydratedManifestsRequest{}
- _, err := service.CommitHydratedManifests(t.Context(), request)
+ _, err := service.CommitHydratedManifests(context.Background(), request)
require.Error(t, err)
assert.ErrorContains(t, err, "repo is required")
})
@@ -44,7 +45,7 @@ func Test_CommitHydratedManifests(t *testing.T) {
request := &apiclient.CommitHydratedManifestsRequest{
Repo: &v1alpha1.Repository{},
}
- _, err := service.CommitHydratedManifests(t.Context(), request)
+ _, err := service.CommitHydratedManifests(context.Background(), request)
require.Error(t, err)
assert.ErrorContains(t, err, "repo URL is required")
})
@@ -58,7 +59,7 @@ func Test_CommitHydratedManifests(t *testing.T) {
Repo: "https://github.com/argoproj/argocd-example-apps.git",
},
}
- _, err := service.CommitHydratedManifests(t.Context(), request)
+ _, err := service.CommitHydratedManifests(context.Background(), request)
require.Error(t, err)
assert.ErrorContains(t, err, "target branch is required")
})
@@ -73,7 +74,7 @@ func Test_CommitHydratedManifests(t *testing.T) {
},
TargetBranch: "main",
}
- _, err := service.CommitHydratedManifests(t.Context(), request)
+ _, err := service.CommitHydratedManifests(context.Background(), request)
require.Error(t, err)
assert.ErrorContains(t, err, "sync branch is required")
})
@@ -84,7 +85,7 @@ func Test_CommitHydratedManifests(t *testing.T) {
service, mockRepoClientFactory := newServiceWithMocks(t)
mockRepoClientFactory.On("NewClient", mock.Anything, mock.Anything).Return(nil, assert.AnError).Once()
- _, err := service.CommitHydratedManifests(t.Context(), validRequest)
+ _, err := service.CommitHydratedManifests(context.Background(), validRequest)
require.Error(t, err)
assert.ErrorIs(t, err, assert.AnError)
})
@@ -104,7 +105,7 @@ func Test_CommitHydratedManifests(t *testing.T) {
mockGitClient.On("CommitSHA").Return("it-worked!", nil).Once()
mockRepoClientFactory.On("NewClient", mock.Anything, mock.Anything).Return(mockGitClient, nil).Once()
- resp, err := service.CommitHydratedManifests(t.Context(), validRequest)
+ resp, err := service.CommitHydratedManifests(context.Background(), validRequest)
require.NoError(t, err)
require.NotNil(t, resp)
assert.Equal(t, "it-worked!", resp.HydratedSha)
diff --git a/commitserver/commit/credentialtypehelper.go b/commitserver/commit/credentialtypehelper.go
index 2eea0a885b..eda3b8040d 100644
--- a/commitserver/commit/credentialtypehelper.go
+++ b/commitserver/commit/credentialtypehelper.go
@@ -1,6 +1,6 @@
package commit
-import "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+import "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
// getCredentialType returns the type of credential used by the repository.
func getCredentialType(repo *v1alpha1.Repository) string {
diff --git a/commitserver/commit/credentialtypehelper_test.go b/commitserver/commit/credentialtypehelper_test.go
index 2bdf97472a..45a013410c 100644
--- a/commitserver/commit/credentialtypehelper_test.go
+++ b/commitserver/commit/credentialtypehelper_test.go
@@ -3,9 +3,7 @@ package commit
import (
"testing"
- "github.com/stretchr/testify/assert"
-
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
)
func TestRepository_GetCredentialType(t *testing.T) {
@@ -56,7 +54,9 @@ func TestRepository_GetCredentialType(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- assert.Equal(t, tt.want, getCredentialType(tt.repo), "Repository.GetCredentialType()")
+ if got := getCredentialType(tt.repo); got != tt.want {
+ t.Errorf("Repository.GetCredentialType() = %v, want %v", got, tt.want)
+ }
})
}
}
diff --git a/commitserver/commit/hydratorhelper.go b/commitserver/commit/hydratorhelper.go
index 18fd0c8073..a4fbeb591b 100644
--- a/commitserver/commit/hydratorhelper.go
+++ b/commitserver/commit/hydratorhelper.go
@@ -11,13 +11,13 @@ import (
"gopkg.in/yaml.v3"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
- "github.com/argoproj/argo-cd/v3/commitserver/apiclient"
- "github.com/argoproj/argo-cd/v3/util/io/files"
+ "github.com/argoproj/argo-cd/v2/commitserver/apiclient"
+ "github.com/argoproj/argo-cd/v2/util/io/files"
)
// WriteForPaths writes the manifests, hydrator.metadata, and README.md files for each path in the provided paths. It
// also writes a root-level hydrator.metadata file containing the repo URL and dry SHA.
-func WriteForPaths(rootPath string, repoUrl string, drySha string, paths []*apiclient.PathDetails) error { //nolint:revive //FIXME(var-naming)
+func WriteForPaths(rootPath string, repoUrl string, drySha string, paths []*apiclient.PathDetails) error {
// Write the top-level readme.
err := writeMetadata(rootPath, hydratorMetadataFile{DrySHA: drySha, RepoURL: repoUrl})
if err != nil {
@@ -64,13 +64,13 @@ func WriteForPaths(rootPath string, repoUrl string, drySha string, paths []*apic
// writeMetadata writes the metadata to the hydrator.metadata file.
func writeMetadata(dirPath string, metadata hydratorMetadataFile) error {
- hydratorMetadataJSON, err := json.MarshalIndent(metadata, "", " ")
+ hydratorMetadataJson, err := json.MarshalIndent(metadata, "", " ")
if err != nil {
return fmt.Errorf("failed to marshal hydrator metadata: %w", err)
}
// No need to use SecureJoin here, as the path is already sanitized.
hydratorMetadataPath := path.Join(dirPath, "hydrator.metadata")
- err = os.WriteFile(hydratorMetadataPath, hydratorMetadataJSON, os.ModePerm)
+ err = os.WriteFile(hydratorMetadataPath, hydratorMetadataJson, os.ModePerm)
if err != nil {
return fmt.Errorf("failed to write hydrator metadata: %w", err)
}
diff --git a/commitserver/commit/hydratorhelper_test.go b/commitserver/commit/hydratorhelper_test.go
index e2e5e06f2e..51e8adf0c6 100644
--- a/commitserver/commit/hydratorhelper_test.go
+++ b/commitserver/commit/hydratorhelper_test.go
@@ -10,13 +10,13 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
- "github.com/argoproj/argo-cd/v3/commitserver/apiclient"
+ "github.com/argoproj/argo-cd/v2/commitserver/apiclient"
)
func TestWriteForPaths(t *testing.T) {
dir := t.TempDir()
- repoURL := "https://github.com/example/repo"
+ repoUrl := "https://github.com/example/repo"
drySha := "abc123"
paths := []*apiclient.PathDetails{
{
@@ -35,7 +35,7 @@ func TestWriteForPaths(t *testing.T) {
},
}
- err := WriteForPaths(dir, repoURL, drySha, paths)
+ err := WriteForPaths(dir, repoUrl, drySha, paths)
require.NoError(t, err)
// Check if the top-level hydrator.metadata exists and contains the repo URL and dry SHA
@@ -46,7 +46,7 @@ func TestWriteForPaths(t *testing.T) {
var topMetadata hydratorMetadataFile
err = json.Unmarshal(topMetadataBytes, &topMetadata)
require.NoError(t, err)
- assert.Equal(t, repoURL, topMetadata.RepoURL)
+ assert.Equal(t, repoUrl, topMetadata.RepoURL)
assert.Equal(t, drySha, topMetadata.DrySHA)
for _, p := range paths {
@@ -64,13 +64,13 @@ func TestWriteForPaths(t *testing.T) {
var readMetadata hydratorMetadataFile
err = json.Unmarshal(metadataBytes, &readMetadata)
require.NoError(t, err)
- assert.Equal(t, repoURL, readMetadata.RepoURL)
+ assert.Equal(t, repoUrl, readMetadata.RepoURL)
// Check if each path contains a README.md file and contains the repo URL
readmePath := path.Join(fullHydratePath, "README.md")
readmeBytes, err := os.ReadFile(readmePath)
require.NoError(t, err)
- assert.Contains(t, string(readmeBytes), repoURL)
+ assert.Contains(t, string(readmeBytes), repoUrl)
// Check if each path contains a manifest.yaml file and contains the word Pod
manifestPath := path.Join(fullHydratePath, "manifest.yaml")
diff --git a/commitserver/commit/mocks/RepoClientFactory.go b/commitserver/commit/mocks/RepoClientFactory.go
index eb571c9018..7c2a2afa49 100644
--- a/commitserver/commit/mocks/RepoClientFactory.go
+++ b/commitserver/commit/mocks/RepoClientFactory.go
@@ -1,15 +1,49 @@
-// Code generated by mockery; DO NOT EDIT.
-// github.com/vektra/mockery
-// template: testify
+// Code generated by mockery v2.53.4. DO NOT EDIT.
package mocks
import (
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- "github.com/argoproj/argo-cd/v3/util/git"
+ git "github.com/argoproj/argo-cd/v2/util/git"
mock "github.com/stretchr/testify/mock"
+
+ v1alpha1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
)
+// RepoClientFactory is an autogenerated mock type for the RepoClientFactory type
+type RepoClientFactory struct {
+ mock.Mock
+}
+
+// NewClient provides a mock function with given fields: repo, rootPath
+func (_m *RepoClientFactory) NewClient(repo *v1alpha1.Repository, rootPath string) (git.Client, error) {
+ ret := _m.Called(repo, rootPath)
+
+ if len(ret) == 0 {
+ panic("no return value specified for NewClient")
+ }
+
+ var r0 git.Client
+ var r1 error
+ if rf, ok := ret.Get(0).(func(*v1alpha1.Repository, string) (git.Client, error)); ok {
+ return rf(repo, rootPath)
+ }
+ if rf, ok := ret.Get(0).(func(*v1alpha1.Repository, string) git.Client); ok {
+ r0 = rf(repo, rootPath)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(git.Client)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(*v1alpha1.Repository, string) error); ok {
+ r1 = rf(repo, rootPath)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
// NewRepoClientFactory creates a new instance of RepoClientFactory. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
// The first argument is typically a *testing.T value.
func NewRepoClientFactory(t interface {
@@ -23,73 +57,3 @@ func NewRepoClientFactory(t interface {
return mock
}
-
-// RepoClientFactory is an autogenerated mock type for the RepoClientFactory type
-type RepoClientFactory struct {
- mock.Mock
-}
-
-type RepoClientFactory_Expecter struct {
- mock *mock.Mock
-}
-
-func (_m *RepoClientFactory) EXPECT() *RepoClientFactory_Expecter {
- return &RepoClientFactory_Expecter{mock: &_m.Mock}
-}
-
-// NewClient provides a mock function for the type RepoClientFactory
-func (_mock *RepoClientFactory) NewClient(repo *v1alpha1.Repository, rootPath string) (git.Client, error) {
- ret := _mock.Called(repo, rootPath)
-
- if len(ret) == 0 {
- panic("no return value specified for NewClient")
- }
-
- var r0 git.Client
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(*v1alpha1.Repository, string) (git.Client, error)); ok {
- return returnFunc(repo, rootPath)
- }
- if returnFunc, ok := ret.Get(0).(func(*v1alpha1.Repository, string) git.Client); ok {
- r0 = returnFunc(repo, rootPath)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(git.Client)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(*v1alpha1.Repository, string) error); ok {
- r1 = returnFunc(repo, rootPath)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// RepoClientFactory_NewClient_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'NewClient'
-type RepoClientFactory_NewClient_Call struct {
- *mock.Call
-}
-
-// NewClient is a helper method to define mock.On call
-// - repo
-// - rootPath
-func (_e *RepoClientFactory_Expecter) NewClient(repo interface{}, rootPath interface{}) *RepoClientFactory_NewClient_Call {
- return &RepoClientFactory_NewClient_Call{Call: _e.mock.On("NewClient", repo, rootPath)}
-}
-
-func (_c *RepoClientFactory_NewClient_Call) Run(run func(repo *v1alpha1.Repository, rootPath string)) *RepoClientFactory_NewClient_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(*v1alpha1.Repository), args[1].(string))
- })
- return _c
-}
-
-func (_c *RepoClientFactory_NewClient_Call) Return(client git.Client, err error) *RepoClientFactory_NewClient_Call {
- _c.Call.Return(client, err)
- return _c
-}
-
-func (_c *RepoClientFactory_NewClient_Call) RunAndReturn(run func(repo *v1alpha1.Repository, rootPath string) (git.Client, error)) *RepoClientFactory_NewClient_Call {
- _c.Call.Return(run)
- return _c
-}
diff --git a/commitserver/commit/repo_client_factory.go b/commitserver/commit/repo_client_factory.go
index 2ebf7c8969..f0f3b5c75d 100644
--- a/commitserver/commit/repo_client_factory.go
+++ b/commitserver/commit/repo_client_factory.go
@@ -1,9 +1,9 @@
package commit
import (
- "github.com/argoproj/argo-cd/v3/commitserver/metrics"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- "github.com/argoproj/argo-cd/v3/util/git"
+ "github.com/argoproj/argo-cd/v2/commitserver/metrics"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/util/git"
)
// RepoClientFactory is a factory for creating git clients for a repository.
diff --git a/commitserver/metrics/githandlers.go b/commitserver/metrics/githandlers.go
index 0005b3a8c9..4a960ebd54 100644
--- a/commitserver/metrics/githandlers.go
+++ b/commitserver/metrics/githandlers.go
@@ -3,7 +3,7 @@ package metrics
import (
"time"
- "github.com/argoproj/argo-cd/v3/util/git"
+ "github.com/argoproj/argo-cd/v2/util/git"
)
// NewGitClientEventHandlers creates event handlers that update Git related metrics
diff --git a/commitserver/server.go b/commitserver/server.go
index 3404267cae..5e5b63324c 100644
--- a/commitserver/server.go
+++ b/commitserver/server.go
@@ -5,12 +5,12 @@ import (
"google.golang.org/grpc/health"
"google.golang.org/grpc/health/grpc_health_v1"
- "github.com/argoproj/argo-cd/v3/commitserver/apiclient"
- "github.com/argoproj/argo-cd/v3/commitserver/commit"
- "github.com/argoproj/argo-cd/v3/commitserver/metrics"
- versionpkg "github.com/argoproj/argo-cd/v3/pkg/apiclient/version"
- "github.com/argoproj/argo-cd/v3/server/version"
- "github.com/argoproj/argo-cd/v3/util/git"
+ "github.com/argoproj/argo-cd/v2/commitserver/apiclient"
+ "github.com/argoproj/argo-cd/v2/commitserver/commit"
+ "github.com/argoproj/argo-cd/v2/commitserver/metrics"
+ versionpkg "github.com/argoproj/argo-cd/v2/pkg/apiclient/version"
+ "github.com/argoproj/argo-cd/v2/server/version"
+ "github.com/argoproj/argo-cd/v2/util/git"
)
// ArgoCDCommitServer is the server that handles commit requests.
diff --git a/common/common.go b/common/common.go
index f43394a22e..82e0d91f72 100644
--- a/common/common.go
+++ b/common/common.go
@@ -2,25 +2,24 @@ package common
import (
"context"
- "errors"
"fmt"
"os"
"path/filepath"
"strconv"
"time"
+ "github.com/pkg/errors"
"github.com/redis/go-redis/v9"
"github.com/sirupsen/logrus"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+ v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
)
// Component names
const (
- ApplicationController = "argocd-application-controller"
- ApplicationSetController = "argocd-applicationset-controller"
+ ApplicationController = "argocd-application-controller"
)
// Default service addresses and URLS of Argo CD internal services
@@ -159,8 +158,6 @@ const (
ArgoCDCLIClientAppName = "Argo CD CLI"
// ArgoCDCLIClientAppID is the Oauth client ID we will use when registering our CLI to dex
ArgoCDCLIClientAppID = "argo-cd-cli"
- // DexFederatedScope allows to receive the federated_claims from Dex. https://dexidp.io/docs/configuration/custom-scopes-claims-clients/
- DexFederatedScope = "federated:id"
)
// Resource metadata labels and annotations (keys and values) used by Argo CD components
@@ -280,8 +277,6 @@ const (
EnvLogLevel = "ARGOCD_LOG_LEVEL"
// EnvLogFormatEnableFullTimestamp enables the FullTimestamp option in logs
EnvLogFormatEnableFullTimestamp = "ARGOCD_LOG_FORMAT_ENABLE_FULL_TIMESTAMP"
- // EnvLogFormatTimestamp is the timestamp format used in logs
- EnvLogFormatTimestamp = "ARGOCD_LOG_FORMAT_TIMESTAMP"
// EnvMaxCookieNumber max number of chunks a cookie can be broken into
EnvMaxCookieNumber = "ARGOCD_MAX_COOKIE_NUMBER"
// EnvPluginSockFilePath allows to override the pluginSockFilePath for repo server and cmp server
@@ -292,8 +287,6 @@ const (
EnvCMPWorkDir = "ARGOCD_CMP_WORKDIR"
// EnvGPGDataPath overrides the location where GPG keyring for signature verification is stored
EnvGPGDataPath = "ARGOCD_GPG_DATA_PATH"
- // EnvServer is the server address of the Argo CD API server.
- EnvServer = "ARGOCD_SERVER"
// EnvServerName is the name of the Argo CD server component, as specified by the value under the LabelKeyAppName label key.
EnvServerName = "ARGOCD_SERVER_NAME"
// EnvRepoServerName is the name of the Argo CD repo server component, as specified by the value under the LabelKeyAppName label key.
@@ -361,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 {
- gnuPgHome := os.Getenv(EnvGnuPGHome)
- if gnuPgHome == "" {
+ if gnuPgHome := os.Getenv(EnvGnuPGHome); 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 {
- pluginSockFilePath := os.Getenv(EnvPluginSockFilePath)
- if pluginSockFilePath == "" {
+ if pluginSockFilePath := os.Getenv(EnvPluginSockFilePath); pluginSockFilePath == "" {
return DefaultPluginSockFilePath
+ } else {
+ return pluginSockFilePath
}
- return pluginSockFilePath
}
// GetCMPChunkSize will return the env var EnvCMPChunkSize value if defined or DefaultCMPChunkSize otherwise.
@@ -444,7 +437,7 @@ const (
// TokenVerificationError is a generic error message for a failure to verify a JWT
const TokenVerificationError = "failed to verify the token"
-var ErrTokenVerification = errors.New(TokenVerificationError)
+var TokenVerificationErr = errors.New(TokenVerificationError)
var PermissionDeniedAPIError = status.Error(codes.PermissionDenied, "permission denied")
@@ -462,7 +455,7 @@ SetOptionalRedisPasswordFromKubeConfig sets the optional Redis password if it ex
We specify kubeClient as kubernetes.Interface to allow for mocking in tests, but this should be treated as a kubernetes.Clientset param.
*/
func SetOptionalRedisPasswordFromKubeConfig(ctx context.Context, kubeClient kubernetes.Interface, namespace string, redisOptions *redis.Options) error {
- secret, err := kubeClient.CoreV1().Secrets(namespace).Get(ctx, RedisInitialCredentials, metav1.GetOptions{})
+ secret, err := kubeClient.CoreV1().Secrets(namespace).Get(ctx, RedisInitialCredentials, v1.GetOptions{})
if err != nil {
return fmt.Errorf("failed to get secret %s/%s: %w", namespace, RedisInitialCredentials, err)
}
diff --git a/common/common_test.go b/common/common_test.go
index 87e0f3474e..5fc8faf2a2 100644
--- a/common/common_test.go
+++ b/common/common_test.go
@@ -1,7 +1,9 @@
package common
import (
+ "context"
"fmt"
+ "os"
"strconv"
"testing"
"time"
@@ -27,7 +29,7 @@ func Test_GRPCKeepAliveMinNotSet(t *testing.T) {
// Test valid env var set for EnvGRPCKeepAliveMin
func Test_GRPCKeepAliveMinIsSet(t *testing.T) {
numSeconds := 15
- t.Setenv(EnvGRPCKeepAliveMin, fmt.Sprintf("%ds", numSeconds))
+ os.Setenv(EnvGRPCKeepAliveMin, fmt.Sprintf("%ds", numSeconds))
grpcKeepAliveMin := GetGRPCKeepAliveEnforcementMinimum()
grpcKeepAliveExpectedMin := time.Duration(numSeconds) * time.Second
@@ -40,7 +42,7 @@ func Test_GRPCKeepAliveMinIsSet(t *testing.T) {
// Test invalid env var set for EnvGRPCKeepAliveMin
func Test_GRPCKeepAliveMinIncorrectlySet(t *testing.T) {
numSeconds := 15
- t.Setenv(EnvGRPCKeepAliveMin, strconv.Itoa(numSeconds))
+ os.Setenv(EnvGRPCKeepAliveMin, strconv.Itoa(numSeconds))
grpcKeepAliveMin := GetGRPCKeepAliveEnforcementMinimum()
grpcKeepAliveExpectedMin := defaultGRPCKeepAliveEnforcementMinimum
@@ -70,7 +72,7 @@ func TestSetOptionalRedisPasswordFromKubeConfig(t *testing.T) {
name: "Secret does not exist",
namespace: "default",
expectedPassword: "",
- expectedErr: "failed to get secret default/" + RedisInitialCredentials,
+ expectedErr: fmt.Sprintf("failed to get secret default/%s", RedisInitialCredentials),
secret: nil,
},
{
@@ -89,13 +91,14 @@ func TestSetOptionalRedisPasswordFromKubeConfig(t *testing.T) {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
var (
- ctx = t.Context()
+ ctx = context.TODO()
kubeClient = kubefake.NewClientset()
redisOptions = &redis.Options{}
)
if tc.secret != nil {
- _, err := kubeClient.CoreV1().Secrets(tc.namespace).Create(ctx, tc.secret, metav1.CreateOptions{})
- require.NoErrorf(t, err, "Failed to create secret")
+ if _, err := kubeClient.CoreV1().Secrets(tc.namespace).Create(ctx, tc.secret, metav1.CreateOptions{}); err != nil {
+ t.Fatalf("Failed to create secret: %v", err)
+ }
}
err := SetOptionalRedisPasswordFromKubeConfig(ctx, kubeClient, tc.namespace, redisOptions)
if tc.expectedErr != "" {
diff --git a/controller/appcontroller.go b/controller/appcontroller.go
index a82ecac76c..5471f58c35 100644
--- a/controller/appcontroller.go
+++ b/controller/appcontroller.go
@@ -3,7 +3,7 @@ package controller
import (
"context"
"encoding/json"
- stderrors "errors"
+ goerrors "errors"
"fmt"
"math"
"math/rand"
@@ -25,8 +25,8 @@ import (
jsonpatch "github.com/evanphx/json-patch"
log "github.com/sirupsen/logrus"
"golang.org/x/sync/semaphore"
- corev1 "k8s.io/api/core/v1"
- apierrors "k8s.io/apimachinery/pkg/api/errors"
+ 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/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/labels"
@@ -43,33 +43,34 @@ import (
"k8s.io/client-go/util/workqueue"
"k8s.io/utils/ptr"
- commitclient "github.com/argoproj/argo-cd/v3/commitserver/apiclient"
- "github.com/argoproj/argo-cd/v3/common"
- statecache "github.com/argoproj/argo-cd/v3/controller/cache"
- "github.com/argoproj/argo-cd/v3/controller/hydrator"
- "github.com/argoproj/argo-cd/v3/controller/metrics"
- "github.com/argoproj/argo-cd/v3/controller/sharding"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application"
- appv1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- appclientset "github.com/argoproj/argo-cd/v3/pkg/client/clientset/versioned"
- "github.com/argoproj/argo-cd/v3/pkg/client/informers/externalversions/application/v1alpha1"
- applisters "github.com/argoproj/argo-cd/v3/pkg/client/listers/application/v1alpha1"
- "github.com/argoproj/argo-cd/v3/reposerver/apiclient"
- applog "github.com/argoproj/argo-cd/v3/util/app/log"
- "github.com/argoproj/argo-cd/v3/util/argo"
- argodiff "github.com/argoproj/argo-cd/v3/util/argo/diff"
- "github.com/argoproj/argo-cd/v3/util/argo/normalizers"
- "github.com/argoproj/argo-cd/v3/util/env"
- "github.com/argoproj/argo-cd/v3/util/stats"
+ commitclient "github.com/argoproj/argo-cd/v2/commitserver/apiclient"
+ "github.com/argoproj/argo-cd/v2/common"
+ statecache "github.com/argoproj/argo-cd/v2/controller/cache"
+ "github.com/argoproj/argo-cd/v2/controller/hydrator"
+ "github.com/argoproj/argo-cd/v2/controller/metrics"
+ "github.com/argoproj/argo-cd/v2/controller/sharding"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application"
+ appv1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+ appclientset "github.com/argoproj/argo-cd/v2/pkg/client/clientset/versioned"
+ "github.com/argoproj/argo-cd/v2/pkg/client/informers/externalversions/application/v1alpha1"
+ applisters "github.com/argoproj/argo-cd/v2/pkg/client/listers/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/reposerver/apiclient"
+ "github.com/argoproj/argo-cd/v2/util/argo"
+ argodiff "github.com/argoproj/argo-cd/v2/util/argo/diff"
+ "github.com/argoproj/argo-cd/v2/util/argo/normalizers"
+ "github.com/argoproj/argo-cd/v2/util/env"
+ "github.com/argoproj/argo-cd/v2/util/stats"
- "github.com/argoproj/argo-cd/v3/pkg/ratelimiter"
- appstatecache "github.com/argoproj/argo-cd/v3/util/cache/appstate"
- "github.com/argoproj/argo-cd/v3/util/db"
- "github.com/argoproj/argo-cd/v3/util/errors"
- "github.com/argoproj/argo-cd/v3/util/glob"
- "github.com/argoproj/argo-cd/v3/util/helm"
- logutils "github.com/argoproj/argo-cd/v3/util/log"
- settings_util "github.com/argoproj/argo-cd/v3/util/settings"
+ 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"
+ "github.com/argoproj/argo-cd/v2/util/errors"
+ "github.com/argoproj/argo-cd/v2/util/glob"
+ "github.com/argoproj/argo-cd/v2/util/helm"
+ logutils "github.com/argoproj/argo-cd/v2/util/log"
+ settings_util "github.com/argoproj/argo-cd/v2/util/settings"
)
const (
@@ -100,6 +101,15 @@ func (a CompareWith) Pointer() *CompareWith {
return &a
}
+func getAppLog(app *appv1.Application) *log.Entry {
+ return log.WithFields(log.Fields{
+ "application": app.Name,
+ "app-namespace": app.Namespace,
+ "app-qualified-name": app.QualifiedName(),
+ "project": app.Spec.Project,
+ })
+}
+
// ApplicationController is the controller for application resources.
type ApplicationController struct {
cache *appstatecache.Cache
@@ -133,7 +143,6 @@ type ApplicationController struct {
refreshRequestedApps map[string]CompareWith
refreshRequestedAppsMutex *sync.Mutex
metricsServer *metrics.MetricsServer
- metricsClusterLabels []string
kubectlSemaphore *semaphore.Weighted
clusterSharding sharding.ClusterShardingCache
projByNameCache sync.Map
@@ -169,7 +178,6 @@ func NewApplicationController(
metricsCacheExpiration time.Duration,
metricsApplicationLabels []string,
metricsApplicationConditions []string,
- metricsClusterLabels []string,
kubectlParallelismLimit int64,
persistResourceHealth bool,
clusterSharding sharding.ClusterShardingCache,
@@ -216,7 +224,6 @@ func NewApplicationController(
applicationNamespaces: applicationNamespaces,
dynamicClusterDistributionEnabled: dynamicClusterDistributionEnabled,
ignoreNormalizerOpts: ignoreNormalizerOpts,
- metricsClusterLabels: metricsClusterLabels,
}
if hydratorEnabled {
ctrl.hydrator = hydrator.NewHydrator(&ctrl, appResyncPeriod, commitClientset)
@@ -230,7 +237,7 @@ func NewApplicationController(
projInformer := v1alpha1.NewAppProjectInformer(applicationClientset, namespace, appResyncPeriod, indexers)
var err error
_, err = projInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{
- AddFunc: func(obj any) {
+ AddFunc: func(obj interface{}) {
if key, err := cache.MetaNamespaceKeyFunc(obj); err == nil {
ctrl.projectRefreshQueue.AddRateLimited(key)
if projMeta, ok := obj.(metav1.Object); ok {
@@ -238,7 +245,7 @@ func NewApplicationController(
}
}
},
- UpdateFunc: func(_, new any) {
+ UpdateFunc: func(old, new interface{}) {
if key, err := cache.MetaNamespaceKeyFunc(new); err == nil {
ctrl.projectRefreshQueue.AddRateLimited(key)
if projMeta, ok := new.(metav1.Object); ok {
@@ -246,7 +253,7 @@ func NewApplicationController(
}
}
},
- DeleteFunc: func(obj any) {
+ DeleteFunc: func(obj interface{}) {
if key, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj); err == nil {
// immediately push to queue for deletes
ctrl.projectRefreshQueue.Add(key)
@@ -269,47 +276,25 @@ func NewApplicationController(
deploymentInformer = factory.Apps().V1().Deployments()
}
- readinessHealthCheck := func(_ *http.Request) error {
+ readinessHealthCheck := func(r *http.Request) error {
if dynamicClusterDistributionEnabled {
applicationControllerName := env.StringFromEnv(common.EnvAppControllerName, common.DefaultApplicationControllerName)
appControllerDeployment, err := deploymentInformer.Lister().Deployments(settingsMgr.GetNamespace()).Get(applicationControllerName)
if err != nil {
- if !apierrors.IsNotFound(err) {
+ if kubeerrors.IsNotFound(err) {
+ appControllerDeployment = nil
+ } else {
return fmt.Errorf("error retrieving Application Controller Deployment: %w", err)
}
- appControllerDeployment = nil
}
if appControllerDeployment != nil {
if appControllerDeployment.Spec.Replicas != nil && int(*appControllerDeployment.Spec.Replicas) <= 0 {
return fmt.Errorf("application controller deployment replicas is not set or is less than 0, replicas: %d", appControllerDeployment.Spec.Replicas)
}
shard := env.ParseNumFromEnv(common.EnvControllerShard, -1, -math.MaxInt32, math.MaxInt32)
- shard, err := sharding.GetOrUpdateShardFromConfigMap(kubeClientset.(*kubernetes.Clientset), settingsMgr, int(*appControllerDeployment.Spec.Replicas), shard)
- if err != nil {
+ if _, err := sharding.GetOrUpdateShardFromConfigMap(kubeClientset.(*kubernetes.Clientset), settingsMgr, int(*appControllerDeployment.Spec.Replicas), shard); err != nil {
return fmt.Errorf("error while updating the heartbeat for to the Shard Mapping ConfigMap: %w", err)
}
-
- // update the shard number in the clusterSharding, and resync all applications if the shard number is updated
- if ctrl.clusterSharding.UpdateShard(shard) {
- // update shard number in stateCache
- ctrl.stateCache.UpdateShard(shard)
-
- // resync all applications
- apps, err := ctrl.appLister.List(labels.Everything())
- if err != nil {
- return err
- }
- for _, app := range apps {
- if !ctrl.canProcessApp(app) {
- continue
- }
- key, err := cache.MetaNamespaceKeyFunc(app)
- if err == nil {
- ctrl.appRefreshQueue.AddRateLimited(key)
- ctrl.clusterSharding.AddApp(app)
- }
- }
- }
}
}
return nil
@@ -345,7 +330,7 @@ func (ctrl *ApplicationController) InvalidateProjectsCache(names ...string) {
ctrl.projByNameCache.Delete(name)
}
} else if ctrl != nil {
- ctrl.projByNameCache.Range(func(key, _ any) bool {
+ ctrl.projByNameCache.Range(func(key, _ interface{}) bool {
ctrl.projByNameCache.Delete(key)
return true
})
@@ -372,7 +357,7 @@ func (ctrl *ApplicationController) onKubectlRun(command string) (kube.CleanupFun
}, nil
}
-func isSelfReferencedApp(app *appv1.Application, ref corev1.ObjectReference) bool {
+func isSelfReferencedApp(app *appv1.Application, ref v1.ObjectReference) bool {
gvk := ref.GroupVersionKind()
return ref.UID == app.UID &&
ref.Name == app.Name &&
@@ -402,7 +387,7 @@ func (projCache *appProjCache) GetAppProject(ctx context.Context) (*appv1.AppPro
if projCache.appProj != nil {
return projCache.appProj, nil
}
- proj, err := argo.GetAppProjectByName(ctx, projCache.name, applisters.NewAppProjectLister(projCache.ctrl.projInformer.GetIndexer()), projCache.ctrl.namespace, projCache.ctrl.settingsMgr, projCache.ctrl.db)
+ proj, err := argo.GetAppProjectByName(projCache.name, applisters.NewAppProjectLister(projCache.ctrl.projInformer.GetIndexer()), projCache.ctrl.namespace, projCache.ctrl.settingsMgr, projCache.ctrl.db, ctx)
if err != nil {
return nil, err
}
@@ -419,10 +404,11 @@ func (ctrl *ApplicationController) getAppProj(app *appv1.Application) (*appv1.Ap
}
proj, err := projCache.(*appProjCache).GetAppProject(context.TODO())
if err != nil {
- if apierrors.IsNotFound(err) {
+ if apierr.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())
@@ -430,7 +416,7 @@ func (ctrl *ApplicationController) getAppProj(app *appv1.Application) (*appv1.Ap
return proj, nil
}
-func (ctrl *ApplicationController) handleObjectUpdated(managedByApp map[string]bool, ref corev1.ObjectReference) {
+func (ctrl *ApplicationController) handleObjectUpdated(managedByApp map[string]bool, ref v1.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
@@ -461,7 +447,7 @@ func (ctrl *ApplicationController) handleObjectUpdated(managedByApp map[string]b
continue
}
- logCtx := log.WithFields(applog.GetAppLogFields(app))
+ logCtx := getAppLog(app)
// Enforce application's permission for the source namespace
_, err = ctrl.getAppProj(app)
if err != nil {
@@ -494,22 +480,22 @@ func (ctrl *ApplicationController) handleObjectUpdated(managedByApp map[string]b
// setAppManagedResources will build a list of ResourceDiff based on the provided comparisonResult
// and persist app resources related data in the cache. Will return the persisted ApplicationTree.
-func (ctrl *ApplicationController) setAppManagedResources(destCluster *appv1.Cluster, a *appv1.Application, comparisonResult *comparisonResult) (*appv1.ApplicationTree, error) {
+func (ctrl *ApplicationController) setAppManagedResources(a *appv1.Application, comparisonResult *comparisonResult) (*appv1.ApplicationTree, error) {
ts := stats.NewTimingStats()
defer func() {
- logCtx := log.WithFields(applog.GetAppLogFields(a))
+ logCtx := getAppLog(a)
for k, v := range ts.Timings() {
logCtx = logCtx.WithField(k, v.Milliseconds())
}
logCtx = logCtx.WithField("time_ms", time.Since(ts.StartTime).Milliseconds())
logCtx.Debug("Finished setting app managed resources")
}()
- managedResources, err := ctrl.hideSecretData(destCluster, a, comparisonResult)
+ managedResources, err := ctrl.hideSecretData(a, comparisonResult)
ts.AddCheckpoint("hide_secret_data_ms")
if err != nil {
return nil, fmt.Errorf("error getting managed resources: %w", err)
}
- tree, err := ctrl.getResourceTree(destCluster, a, managedResources)
+ tree, err := ctrl.getResourceTree(a, managedResources)
ts.AddCheckpoint("get_resource_tree_ms")
if err != nil {
return nil, fmt.Errorf("error getting resource tree: %w", err)
@@ -551,10 +537,10 @@ func isKnownOrphanedResourceExclusion(key kube.ResourceKey, proj *appv1.AppProje
return false
}
-func (ctrl *ApplicationController) getResourceTree(destCluster *appv1.Cluster, a *appv1.Application, managedResources []*appv1.ResourceDiff) (*appv1.ApplicationTree, error) {
+func (ctrl *ApplicationController) getResourceTree(a *appv1.Application, managedResources []*appv1.ResourceDiff) (*appv1.ApplicationTree, error) {
ts := stats.NewTimingStats()
defer func() {
- logCtx := log.WithFields(applog.GetAppLogFields(a))
+ logCtx := getAppLog(a)
for k, v := range ts.Timings() {
logCtx = logCtx.WithField(k, v.Milliseconds())
}
@@ -571,7 +557,7 @@ func (ctrl *ApplicationController) getResourceTree(destCluster *appv1.Cluster, a
orphanedNodesMap := make(map[kube.ResourceKey]appv1.ResourceNode)
warnOrphaned := true
if proj.Spec.OrphanedResources != nil {
- orphanedNodesMap, err = ctrl.stateCache.GetNamespaceTopLevelResources(destCluster, a.Spec.Destination.Namespace)
+ orphanedNodesMap, err = ctrl.stateCache.GetNamespaceTopLevelResources(a.Spec.Destination.Server, a.Spec.Destination.Namespace)
if err != nil {
return nil, fmt.Errorf("failed to get namespace top-level resources: %w", err)
}
@@ -607,8 +593,8 @@ func (ctrl *ApplicationController) getResourceTree(destCluster *appv1.Cluster, a
managedResourcesKeys = append(managedResourcesKeys, kube.GetResourceKey(live))
}
}
- err = ctrl.stateCache.IterateHierarchyV2(destCluster, managedResourcesKeys, func(child appv1.ResourceNode, _ string) bool {
- permitted, _ := proj.IsResourcePermitted(schema.GroupKind{Group: child.Group, Kind: child.Kind}, child.Namespace, destCluster, func(project string) ([]*appv1.Cluster, error) {
+ err = ctrl.stateCache.IterateHierarchyV2(a.Spec.Destination.Server, managedResourcesKeys, func(child appv1.ResourceNode, appName 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 {
return nil, fmt.Errorf("failed to get project clusters: %w", err)
@@ -632,7 +618,7 @@ func (ctrl *ApplicationController) getResourceTree(destCluster *appv1.Cluster, a
orphanedNodesKeys = append(orphanedNodesKeys, k)
}
}
- err = ctrl.stateCache.IterateHierarchyV2(destCluster, orphanedNodesKeys, func(child appv1.ResourceNode, appName string) bool {
+ err = ctrl.stateCache.IterateHierarchyV2(a.Spec.Destination.Server, orphanedNodesKeys, func(child appv1.ResourceNode, appName string) bool {
belongToAnotherApp := false
if appName != "" {
appKey := ctrl.toAppKey(appName)
@@ -645,7 +631,7 @@ func (ctrl *ApplicationController) getResourceTree(destCluster *appv1.Cluster, a
return false
}
- permitted, _ := proj.IsResourcePermitted(schema.GroupKind{Group: child.Group, Kind: child.Kind}, child.Namespace, destCluster, func(project string) ([]*appv1.Cluster, error) {
+ permitted, _ := proj.IsResourcePermitted(schema.GroupKind{Group: child.ResourceRef.Group, Kind: child.ResourceRef.Kind}, child.Namespace, a.Spec.Destination, func(project string) ([]*appv1.Cluster, error) {
return ctrl.db.GetProjectClusters(context.TODO(), project)
})
@@ -673,7 +659,7 @@ func (ctrl *ApplicationController) getResourceTree(destCluster *appv1.Cluster, a
})
ts.AddCheckpoint("process_orphaned_resources_ms")
- hosts, err := ctrl.getAppHosts(destCluster, a, nodes)
+ hosts, err := ctrl.getAppHosts(a, nodes)
if err != nil {
return nil, fmt.Errorf("failed to get app hosts: %w", err)
}
@@ -681,20 +667,20 @@ func (ctrl *ApplicationController) getResourceTree(destCluster *appv1.Cluster, a
return &appv1.ApplicationTree{Nodes: nodes, OrphanedNodes: orphanedNodes, Hosts: hosts}, nil
}
-func (ctrl *ApplicationController) getAppHosts(destCluster *appv1.Cluster, a *appv1.Application, appNodes []appv1.ResourceNode) ([]appv1.HostInfo, error) {
+func (ctrl *ApplicationController) getAppHosts(a *appv1.Application, appNodes []appv1.ResourceNode) ([]appv1.HostInfo, error) {
ts := stats.NewTimingStats()
defer func() {
- logCtx := log.WithFields(applog.GetAppLogFields(a))
+ logCtx := getAppLog(a)
for k, v := range ts.Timings() {
logCtx = logCtx.WithField(k, v.Milliseconds())
}
logCtx = logCtx.WithField("time_ms", time.Since(ts.StartTime).Milliseconds())
logCtx.Debug("Finished getting app hosts")
}()
- supportedResourceNames := map[corev1.ResourceName]bool{
- corev1.ResourceCPU: true,
- corev1.ResourceStorage: true,
- corev1.ResourceMemory: true,
+ supportedResourceNames := map[v1.ResourceName]bool{
+ v1.ResourceCPU: true,
+ v1.ResourceStorage: true,
+ v1.ResourceMemory: true,
}
appPods := map[kube.ResourceKey]bool{}
for _, node := range appNodes {
@@ -706,7 +692,7 @@ func (ctrl *ApplicationController) getAppHosts(destCluster *appv1.Cluster, a *ap
allNodesInfo := map[string]statecache.NodeInfo{}
allPodsByNode := map[string][]statecache.PodInfo{}
appPodsByNode := map[string][]statecache.PodInfo{}
- err := ctrl.stateCache.IterateResources(destCluster, func(res *clustercache.Resource, info *statecache.ResourceInfo) {
+ err := ctrl.stateCache.IterateResources(a.Spec.Destination.Server, func(res *clustercache.Resource, info *statecache.ResourceInfo) {
key := res.ResourceKey()
switch {
@@ -734,7 +720,7 @@ func (ctrl *ApplicationController) getAppHosts(destCluster *appv1.Cluster, a *ap
neighbors := allPodsByNode[nodeName]
- resources := map[corev1.ResourceName]appv1.HostResourceInfo{}
+ resources := map[v1.ResourceName]appv1.HostResourceInfo{}
for name, resource := range node.Capacity {
info := resources[name]
info.ResourceName = name
@@ -756,7 +742,7 @@ func (ctrl *ApplicationController) getAppHosts(destCluster *appv1.Cluster, a *ap
for _, pod := range neighbors {
for name, resource := range pod.ResourceRequests {
- if !supportedResourceNames[name] || pod.Phase == corev1.PodSucceeded || pod.Phase == corev1.PodFailed {
+ if !supportedResourceNames[name] || pod.Phase == v1.PodSucceeded || pod.Phase == v1.PodFailed {
continue
}
info := resources[name]
@@ -780,7 +766,7 @@ func (ctrl *ApplicationController) getAppHosts(destCluster *appv1.Cluster, a *ap
return hosts, nil
}
-func (ctrl *ApplicationController) hideSecretData(destCluster *appv1.Cluster, app *appv1.Application, comparisonResult *comparisonResult) ([]*appv1.ResourceDiff, error) {
+func (ctrl *ApplicationController) hideSecretData(app *appv1.Application, comparisonResult *comparisonResult) ([]*appv1.ResourceDiff, error) {
items := make([]*appv1.ResourceDiff, len(comparisonResult.managedResources))
for i := range comparisonResult.managedResources {
res := comparisonResult.managedResources[i]
@@ -819,7 +805,7 @@ func (ctrl *ApplicationController) hideSecretData(destCluster *appv1.Cluster, ap
return nil, fmt.Errorf("error getting tracking method: %w", err)
}
- clusterCache, err := ctrl.stateCache.GetClusterCache(destCluster)
+ clusterCache, err := ctrl.stateCache.GetClusterCache(app.Spec.Destination.Server)
if err != nil {
return nil, fmt.Errorf("error getting cluster cache: %w", err)
}
@@ -879,8 +865,11 @@ func (ctrl *ApplicationController) Run(ctx context.Context, statusProcessors int
defer ctrl.appHydrateQueue.ShutDown()
defer ctrl.hydrationQueue.ShutDown()
+ ctrl.metricsServer.RegisterClustersInfoSource(ctx, ctrl.stateCache)
ctrl.RegisterClusterSecretUpdater(ctx)
- ctrl.metricsServer.RegisterClustersInfoSource(ctx, ctrl.stateCache, ctrl.db, ctrl.metricsClusterLabels)
+
+ go ctrl.appInformer.Run(ctx.Done())
+ go ctrl.projInformer.Run(ctx.Done())
if ctrl.dynamicClusterDistributionEnabled {
// only start deployment informer if dynamic distribution is enabled
@@ -900,9 +889,6 @@ func (ctrl *ApplicationController) Run(ctx context.Context, statusProcessors int
}
}
- go ctrl.appInformer.Run(ctx.Done())
- go ctrl.projInformer.Run(ctx.Done())
-
errors.CheckError(ctrl.stateCache.Init())
if !cache.WaitForCacheSync(ctx.Done(), ctrl.appInformer.HasSynced, ctrl.projInformer.HasSynced) {
@@ -1012,7 +998,7 @@ func (ctrl *ApplicationController) processAppOperationQueueItem() (processNext b
return
}
app := origApp.DeepCopy()
- logCtx := log.WithFields(applog.GetAppLogFields(app))
+ logCtx := getAppLog(app)
ts := stats.NewTimingStats()
defer func() {
for k, v := range ts.Timings() {
@@ -1026,7 +1012,7 @@ func (ctrl *ApplicationController) processAppOperationQueueItem() (processNext b
// If we get here, we are about to process an operation, but we cannot rely on informer since it might have stale data.
// So always retrieve the latest version to ensure it is not stale to avoid unnecessary syncing.
// We cannot rely on informer since applications might be updated by both application controller and api server.
- freshApp, err := ctrl.applicationClientset.ArgoprojV1alpha1().Applications(app.ObjectMeta.Namespace).Get(context.Background(), app.Name, metav1.GetOptions{})
+ freshApp, err := ctrl.applicationClientset.ArgoprojV1alpha1().Applications(app.ObjectMeta.Namespace).Get(context.Background(), app.ObjectMeta.Name, metav1.GetOptions{})
if err != nil {
logCtx.Errorf("Failed to retrieve latest application state: %v", err)
return
@@ -1047,7 +1033,7 @@ func (ctrl *ApplicationController) processAppOperationQueueItem() (processNext b
Message: err.Error(),
})
message := fmt.Sprintf("Unable to delete application resources: %v", err.Error())
- ctrl.logAppEvent(context.TODO(), app, argo.EventInfo{Reason: argo.EventReasonStatusRefreshed, Type: corev1.EventTypeWarning}, message)
+ ctrl.logAppEvent(app, argo.EventInfo{Reason: argo.EventReasonStatusRefreshed, Type: v1.EventTypeWarning}, message, context.TODO())
}
ts.AddCheckpoint("finalize_application_deletion_ms")
}
@@ -1072,12 +1058,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 {
- compareWith, err := strconv.Atoi(parts[2])
- if err != nil {
+ if compareWith, err := strconv.Atoi(parts[2]); 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
}
@@ -1132,16 +1118,17 @@ 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
}
func (ctrl *ApplicationController) removeProjectFinalizer(proj *appv1.AppProject) error {
proj.RemoveFinalizer()
var patch []byte
- patch, _ = json.Marshal(map[string]any{
- "metadata": map[string]any{
+ patch, _ = json.Marshal(map[string]interface{}{
+ "metadata": map[string]interface{}{
"finalizers": proj.Finalizers,
},
})
@@ -1156,14 +1143,14 @@ func (ctrl *ApplicationController) shouldBeDeleted(app *appv1.Application, obj *
!resourceutil.HasAnnotationOption(obj, helm.ResourcePolicyAnnotation, helm.ResourcePolicyKeep)
}
-func (ctrl *ApplicationController) getPermittedAppLiveObjects(destCluster *appv1.Cluster, app *appv1.Application, proj *appv1.AppProject, projectClusters func(project string) ([]*appv1.Cluster, error)) (map[kube.ResourceKey]*unstructured.Unstructured, error) {
- objsMap, err := ctrl.stateCache.GetManagedLiveObjs(destCluster, app, []*unstructured.Unstructured{})
+func (ctrl *ApplicationController) getPermittedAppLiveObjects(app *appv1.Application, proj *appv1.AppProject, projectClusters func(project string) ([]*appv1.Cluster, error)) (map[kube.ResourceKey]*unstructured.Unstructured, error) {
+ objsMap, err := ctrl.stateCache.GetManagedLiveObjs(app, []*unstructured.Unstructured{})
if err != nil {
return nil, err
}
// Don't delete live resources which are not permitted in the app project
for k, v := range objsMap {
- permitted, err := proj.IsLiveResourcePermitted(v, destCluster, projectClusters)
+ permitted, err := proj.IsLiveResourcePermitted(v, app.Spec.Destination.Server, app.Spec.Destination.Name, projectClusters)
if err != nil {
return nil, err
}
@@ -1175,12 +1162,29 @@ func (ctrl *ApplicationController) getPermittedAppLiveObjects(destCluster *appv1
return objsMap, nil
}
+func (ctrl *ApplicationController) isValidDestination(app *appv1.Application) (bool, *appv1.Cluster) {
+ logCtx := getAppLog(app)
+ // Validate the cluster using the Application destination's `name` field, if applicable,
+ // and set the Server field, if needed.
+ if err := argo.ValidateDestination(context.Background(), &app.Spec.Destination, ctrl.db); err != nil {
+ logCtx.Warnf("Unable to validate destination of the Application being deleted: %v", err)
+ return false, nil
+ }
+
+ cluster, err := ctrl.db.GetCluster(context.Background(), app.Spec.Destination.Server)
+ if err != nil {
+ logCtx.Warnf("Unable to locate cluster URL for Application being deleted: %v", err)
+ return false, nil
+ }
+ return true, cluster
+}
+
func (ctrl *ApplicationController) finalizeApplicationDeletion(app *appv1.Application, projectClusters func(project string) ([]*appv1.Cluster, error)) error {
- logCtx := log.WithFields(applog.GetAppLogFields(app))
+ logCtx := getAppLog(app)
// 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 !apierrors.IsNotFound(err) {
+ if !apierr.IsNotFound(err) {
logCtx.Errorf("Unable to get refreshed application info prior deleting resources: %v", err)
}
return nil
@@ -1189,9 +1193,9 @@ func (ctrl *ApplicationController) finalizeApplicationDeletion(app *appv1.Applic
if err != nil {
return err
}
- destCluster, err := argo.GetDestinationCluster(context.Background(), app.Spec.Destination, ctrl.db)
- if err != nil {
- logCtx.Warnf("Unable to get destination cluster: %v", err)
+
+ isValid, cluster := ctrl.isValidDestination(app)
+ if !isValid {
app.UnSetCascadedDeletion()
app.UnSetPostDeleteFinalizer()
if err := ctrl.updateFinalizers(app); err != nil {
@@ -1200,7 +1204,7 @@ func (ctrl *ApplicationController) finalizeApplicationDeletion(app *appv1.Applic
logCtx.Infof("Resource entries removed from undefined cluster")
return nil
}
- clusterRESTConfig, err := destCluster.RESTConfig()
+ clusterRESTConfig, err := cluster.RESTConfig()
if err != nil {
return err
}
@@ -1212,7 +1216,7 @@ func (ctrl *ApplicationController) finalizeApplicationDeletion(app *appv1.Applic
logCtx.Infof("Deleting resources")
// ApplicationDestination points to a valid cluster, so we may clean up the live objects
objs := make([]*unstructured.Unstructured, 0)
- objsMap, err := ctrl.getPermittedAppLiveObjects(destCluster, app, proj, projectClusters)
+ objsMap, err := ctrl.getPermittedAppLiveObjects(app, proj, projectClusters)
if err != nil {
return err
}
@@ -1249,7 +1253,7 @@ func (ctrl *ApplicationController) finalizeApplicationDeletion(app *appv1.Applic
return err
}
- objsMap, err = ctrl.getPermittedAppLiveObjects(destCluster, app, proj, projectClusters)
+ objsMap, err = ctrl.getPermittedAppLiveObjects(app, proj, projectClusters)
if err != nil {
return err
}
@@ -1269,7 +1273,7 @@ func (ctrl *ApplicationController) finalizeApplicationDeletion(app *appv1.Applic
}
if app.HasPostDeleteFinalizer() {
- objsMap, err := ctrl.getPermittedAppLiveObjects(destCluster, app, proj, projectClusters)
+ objsMap, err := ctrl.getPermittedAppLiveObjects(app, proj, projectClusters)
if err != nil {
return err
}
@@ -1286,7 +1290,7 @@ func (ctrl *ApplicationController) finalizeApplicationDeletion(app *appv1.Applic
}
if app.HasPostDeleteFinalizer("cleanup") {
- objsMap, err := ctrl.getPermittedAppLiveObjects(destCluster, app, proj, projectClusters)
+ objsMap, err := ctrl.getPermittedAppLiveObjects(app, proj, projectClusters)
if err != nil {
return err
}
@@ -1323,8 +1327,8 @@ func (ctrl *ApplicationController) updateFinalizers(app *appv1.Application) erro
}
var patch []byte
- patch, _ = json.Marshal(map[string]any{
- "metadata": map[string]any{
+ patch, _ = json.Marshal(map[string]interface{}{
+ "metadata": map[string]interface{}{
"finalizers": app.Finalizers,
},
})
@@ -1334,7 +1338,7 @@ func (ctrl *ApplicationController) updateFinalizers(app *appv1.Application) erro
}
func (ctrl *ApplicationController) setAppCondition(app *appv1.Application, condition appv1.ApplicationCondition) {
- logCtx := log.WithFields(applog.GetAppLogFields(app))
+ logCtx := getAppLog(app)
// do nothing if app already has same condition
for _, c := range app.Status.Conditions {
if c.Message == condition.Message && c.Type == condition.Type {
@@ -1345,8 +1349,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]any{
- "status": map[string]any{
+ patch, err := json.Marshal(map[string]interface{}{
+ "status": map[string]interface{}{
"conditions": app.Status.Conditions,
},
})
@@ -1359,7 +1363,7 @@ func (ctrl *ApplicationController) setAppCondition(app *appv1.Application, condi
}
func (ctrl *ApplicationController) processRequestedAppOperation(app *appv1.Application) {
- logCtx := log.WithFields(applog.GetAppLogFields(app))
+ logCtx := getAppLog(app)
var state *appv1.OperationState
// Recover from any unexpected panics and automatically set the status to be failed
defer func() {
@@ -1387,8 +1391,7 @@ func (ctrl *ApplicationController) processRequestedAppOperation(app *appv1.Appli
state = app.Status.OperationState.DeepCopy()
terminating = state.Phase == synccommon.OperationTerminating
// Failed operation with retry strategy might have be in-progress and has completion time
- switch {
- case state.FinishedAt != nil && !terminating:
+ if state.FinishedAt != nil && !terminating {
retryAt, err := app.Status.OperationState.Operation.Retry.NextRetryAt(state.FinishedAt.Time, state.RetryCount)
if err != nil {
state.Phase = synccommon.OperationFailed
@@ -1401,19 +1404,20 @@ 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
- case ctrl.syncTimeout != time.Duration(0) && time.Now().After(state.StartedAt.Add(ctrl.syncTimeout)) && !terminating:
+ } 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"
ctrl.setOperationState(app, state)
logCtx.Infof("Terminating in-progress operation due to timeout. Started at: %v, timeout: %v", state.StartedAt, ctrl.syncTimeout)
- default:
+ } else {
logCtx.Infof("Resuming in-progress operation. phase: %s, message: %s", state.Phase, state.Message)
}
} else {
@@ -1427,8 +1431,7 @@ func (ctrl *ApplicationController) processRequestedAppOperation(app *appv1.Appli
}
ts.AddCheckpoint("initial_operation_stage_ms")
- // Call GetDestinationCluster to validate the destination cluster.
- if _, err := argo.GetDestinationCluster(context.Background(), app.Spec.Destination, ctrl.db); err != nil {
+ if err := argo.ValidateDestination(context.Background(), &app.Spec.Destination, ctrl.db); err != nil {
state.Phase = synccommon.OperationFailed
state.Message = err.Error()
} else {
@@ -1444,11 +1447,10 @@ func (ctrl *ApplicationController) processRequestedAppOperation(app *appv1.Appli
state.Message = err.Error()
}
- switch state.Phase {
- case synccommon.OperationRunning:
+ if state.Phase == synccommon.OperationRunning {
// It's possible for an app to be terminated while we were operating on it. We do not want
// to clobber the Terminated state with Running. Get the latest app state to check for this.
- freshApp, err := ctrl.applicationClientset.ArgoprojV1alpha1().Applications(app.Namespace).Get(context.Background(), app.Name, metav1.GetOptions{})
+ freshApp, err := ctrl.applicationClientset.ArgoprojV1alpha1().Applications(app.Namespace).Get(context.Background(), app.ObjectMeta.Name, metav1.GetOptions{})
if err == nil {
// App may have lost permissions to use the project meanwhile.
_, err = ctrl.getAppProj(freshApp)
@@ -1464,7 +1466,7 @@ func (ctrl *ApplicationController) processRequestedAppOperation(app *appv1.Appli
// cleanup (e.g. delete jobs, workflows, etc...)
}
}
- case synccommon.OperationFailed, synccommon.OperationError:
+ } else if state.Phase == synccommon.OperationFailed || state.Phase == synccommon.OperationError {
if !terminating && (state.RetryCount < state.Operation.Retry.Limit || state.Operation.Retry.Limit < 0) {
now := metav1.Now()
state.FinishedAt = &now
@@ -1474,7 +1476,7 @@ func (ctrl *ApplicationController) processRequestedAppOperation(app *appv1.Appli
} else {
state.Phase = synccommon.OperationRunning
state.RetryCount++
- state.Message = fmt.Sprintf("%s. Retrying attempt #%d at %s.", state.Message, state.RetryCount, retryAt.Format(time.Kitchen))
+ state.Message = fmt.Sprintf("%s due to application controller sync timeout. Retrying attempt #%d at %s.", state.Message, state.RetryCount, retryAt.Format(time.Kitchen))
}
} else if state.RetryCount > 0 {
state.Message = fmt.Sprintf("%s (retried %d times).", state.Message, state.RetryCount)
@@ -1497,7 +1499,7 @@ func (ctrl *ApplicationController) processRequestedAppOperation(app *appv1.Appli
}
func (ctrl *ApplicationController) setOperationState(app *appv1.Application, state *appv1.OperationState) {
- logCtx := log.WithFields(applog.GetAppLogFields(app))
+ logCtx := getAppLog(app)
if state.Phase == "" {
// expose any bugs where we neglect to set phase
panic("no phase was set")
@@ -1506,8 +1508,8 @@ func (ctrl *ApplicationController) setOperationState(app *appv1.Application, sta
now := metav1.Now()
state.FinishedAt = &now
}
- patch := map[string]any{
- "status": map[string]any{
+ patch := map[string]interface{}{
+ "status": map[string]interface{}{
"operationState": state,
},
}
@@ -1537,7 +1539,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 apierrors.IsNotFound(err) {
+ if apierr.IsNotFound(err) {
return nil
}
// kube.RetryUntilSucceed logs failed attempts at "debug" level, but we want to know if this fails. Log a
@@ -1561,13 +1563,13 @@ func (ctrl *ApplicationController) setOperationState(app *appv1.Application, sta
messages = append(messages, "to", state.SyncResult.Revision)
}
if state.Phase.Successful() {
- eventInfo.Type = corev1.EventTypeNormal
+ eventInfo.Type = v1.EventTypeNormal
messages = append(messages, "succeeded")
} else {
- eventInfo.Type = corev1.EventTypeWarning
+ eventInfo.Type = v1.EventTypeWarning
messages = append(messages, "failed:", state.Message)
}
- ctrl.logAppEvent(context.TODO(), app, eventInfo, strings.Join(messages, " "))
+ ctrl.logAppEvent(app, eventInfo, strings.Join(messages, " "), context.TODO())
ctrl.metricsServer.IncSync(app, state)
}
}
@@ -1575,7 +1577,7 @@ func (ctrl *ApplicationController) setOperationState(app *appv1.Application, sta
// writeBackToInformer writes a just recently updated App back into the informer cache.
// This prevents the situation where the controller operates on a stale app and repeats work
func (ctrl *ApplicationController) writeBackToInformer(app *appv1.Application) {
- logCtx := log.WithFields(applog.GetAppLogFields(app)).WithField("informer-writeBack", true)
+ logCtx := getAppLog(app).WithField("informer-writeBack", true)
err := ctrl.appInformer.GetStore().Update(app)
if err != nil {
logCtx.Errorf("failed to update informer store: %v", err)
@@ -1594,8 +1596,8 @@ func (ctrl *ApplicationController) PatchAppWithWriteBack(ctx context.Context, na
}
func (ctrl *ApplicationController) processAppRefreshQueueItem() (processNext bool) {
- patchDuration := time.Duration(0) // time spent in doing patch/update calls
- setOpDuration := time.Duration(0) // time spent in doing Operation patch calls in autosync
+ patchMs := time.Duration(0) // time spent in doing patch/update calls
+ setOpMs := time.Duration(0) // time spent in doing Operation patch calls in autosync
appKey, shutdown := ctrl.appRefreshQueue.Get()
if shutdown {
processNext = false
@@ -1632,7 +1634,7 @@ func (ctrl *ApplicationController) processAppRefreshQueueItem() (processNext boo
return
}
app := origApp.DeepCopy()
- logCtx := log.WithFields(applog.GetAppLogFields(app)).WithFields(log.Fields{
+ logCtx := getAppLog(app).WithFields(log.Fields{
"comparison-level": comparisonLevel,
"dest-server": origApp.Spec.Destination.Server,
"dest-name": origApp.Spec.Destination.Name,
@@ -1649,40 +1651,37 @@ func (ctrl *ApplicationController) processAppRefreshQueueItem() (processNext boo
}
logCtx.WithFields(log.Fields{
"time_ms": reconcileDuration.Milliseconds(),
- "patch_ms": patchDuration.Milliseconds(),
- "setop_ms": setOpDuration.Milliseconds(),
+ "patch_ms": patchMs.Milliseconds(),
+ "setop_ms": setOpMs.Milliseconds(),
}).Info("Reconciliation completed")
}()
if comparisonLevel == ComparisonWithNothing {
- // If the destination cluster is invalid, fallback to the normal reconciliation flow
- if destCluster, err := argo.GetDestinationCluster(context.Background(), app.Spec.Destination, ctrl.db); err == nil {
- managedResources := make([]*appv1.ResourceDiff, 0)
- if err := ctrl.cache.GetAppManagedResources(app.InstanceName(ctrl.namespace), &managedResources); err == nil {
- var tree *appv1.ApplicationTree
- if tree, err = ctrl.getResourceTree(destCluster, app, managedResources); err == nil {
- app.Status.Summary = tree.GetSummary(app)
- if err := ctrl.cache.SetAppResourcesTree(app.InstanceName(ctrl.namespace), tree); err != nil {
- logCtx.Errorf("Failed to cache resources tree: %v", err)
- return
- }
- }
-
- patchDuration = ctrl.persistAppStatus(origApp, &app.Status)
- return
- }
+ managedResources := make([]*appv1.ResourceDiff, 0)
+ if err := ctrl.cache.GetAppManagedResources(app.InstanceName(ctrl.namespace), &managedResources); err != nil {
logCtx.Warnf("Failed to get cached managed resources for tree reconciliation, fall back to full reconciliation")
+ } else {
+ var tree *appv1.ApplicationTree
+ if tree, err = ctrl.getResourceTree(app, managedResources); err == nil {
+ app.Status.Summary = tree.GetSummary(app)
+ if err := ctrl.cache.SetAppResourcesTree(app.InstanceName(ctrl.namespace), tree); err != nil {
+ logCtx.Errorf("Failed to cache resources tree: %v", err)
+ return
+ }
+ }
+
+ patchMs = ctrl.persistAppStatus(origApp, &app.Status)
+ return
}
}
ts.AddCheckpoint("comparison_with_nothing_ms")
project, hasErrors := ctrl.refreshAppConditions(app)
ts.AddCheckpoint("refresh_app_conditions_ms")
- now := metav1.Now()
if hasErrors {
app.Status.Sync.Status = appv1.SyncStatusCodeUnknown
app.Status.Health.Status = health.HealthStatusUnknown
- patchDuration = ctrl.persistAppStatus(origApp, &app.Status)
+ patchMs = ctrl.persistAppStatus(origApp, &app.Status)
if err := ctrl.cache.SetAppResourcesTree(app.InstanceName(ctrl.namespace), &appv1.ApplicationTree{}); err != nil {
logCtx.Warnf("failed to set app resource tree: %v", err)
@@ -1694,13 +1693,6 @@ func (ctrl *ApplicationController) processAppRefreshQueueItem() (processNext boo
return
}
- destCluster, err := argo.GetDestinationCluster(context.Background(), app.Spec.Destination, ctrl.db)
- if err != nil {
- logCtx.Errorf("Failed to get destination cluster: %v", err)
- // exit the reconciliation. ctrl.refreshAppConditions should have caught the error
- return
- }
-
var localManifests []string
if opState := app.Status.OperationState; opState != nil && opState.Operation.Sync != nil {
localManifests = opState.Operation.Sync.Manifests
@@ -1733,11 +1725,12 @@ func (ctrl *ApplicationController) processAppRefreshQueueItem() (processNext boo
sources = append(sources, app.Spec.GetSource())
}
- compareResult, err := ctrl.appStateManager.CompareAppState(app, project, revisions, sources, refreshType == appv1.RefreshTypeHard, comparisonLevel == CompareWithLatestForceResolve, localManifests, hasMultipleSources, false)
-
+ compareResult, err := ctrl.appStateManager.CompareAppState(app, project, revisions, sources,
+ refreshType == appv1.RefreshTypeHard,
+ comparisonLevel == CompareWithLatestForceResolve, localManifests, hasMultipleSources, false)
ts.AddCheckpoint("compare_app_state_ms")
- if stderrors.Is(err, ErrCompareStateRepo) {
+ if goerrors.Is(err, CompareStateRepoError) {
logCtx.Warnf("Ignoring temporary failed attempt to compare app state against repo: %v", err)
return // short circuit if git error is encountered
}
@@ -1749,7 +1742,7 @@ func (ctrl *ApplicationController) processAppRefreshQueueItem() (processNext boo
ctrl.normalizeApplication(origApp, app)
ts.AddCheckpoint("normalize_application_ms")
- tree, err := ctrl.setAppManagedResources(destCluster, app, compareResult)
+ tree, err := ctrl.setAppManagedResources(app, compareResult)
ts.AddCheckpoint("set_app_managed_resources_ms")
if err != nil {
logCtx.Errorf("Failed to cache app resources: %v", err)
@@ -1759,8 +1752,8 @@ func (ctrl *ApplicationController) processAppRefreshQueueItem() (processNext boo
canSync, _ := project.Spec.SyncWindows.Matches(app).CanSync(false)
if canSync {
- syncErrCond, opDuration := ctrl.autoSync(app, compareResult.syncStatus, compareResult.resources, compareResult.revisionUpdated)
- setOpDuration = opDuration
+ syncErrCond, opMS := ctrl.autoSync(app, compareResult.syncStatus, compareResult.resources, compareResult.revisionUpdated)
+ setOpMs = opMS
if syncErrCond != nil {
app.Status.SetConditions(
[]appv1.ApplicationCondition{*syncErrCond},
@@ -1778,10 +1771,11 @@ func (ctrl *ApplicationController) processAppRefreshQueueItem() (processNext boo
ts.AddCheckpoint("auto_sync_ms")
if app.Status.ReconciledAt == nil || comparisonLevel >= CompareWithLatest {
+ now := metav1.Now()
app.Status.ReconciledAt = &now
}
app.Status.Sync = *compareResult.syncStatus
- app.Status.Health.Status = compareResult.healthStatus
+ app.Status.Health = *compareResult.healthStatus
app.Status.Resources = compareResult.resources
sort.Slice(app.Status.Resources, func(i, j int) bool {
return resourceStatusKey(app.Status.Resources[i]) < resourceStatusKey(app.Status.Resources[j])
@@ -1790,7 +1784,7 @@ func (ctrl *ApplicationController) processAppRefreshQueueItem() (processNext boo
app.Status.SourceTypes = compareResult.appSourceTypes
app.Status.ControllerNamespace = ctrl.namespace
ts.AddCheckpoint("app_status_update_ms")
- patchDuration = ctrl.persistAppStatus(origApp, &app.Status)
+ patchMs = ctrl.persistAppStatus(origApp, &app.Status)
// This is a partly a duplicate of patch_ms, but more descriptive and allows to have measurement for the next step.
ts.AddCheckpoint("persist_app_status_ms")
if (compareResult.hasPostDeleteHooks != app.HasPostDeleteFinalizer() || compareResult.hasPostDeleteHooks != app.HasPostDeleteFinalizer("cleanup")) &&
@@ -1841,7 +1835,7 @@ func (ctrl *ApplicationController) processAppHydrateQueueItem() (processNext boo
ctrl.hydrator.ProcessAppHydrateQueueItem(origApp)
- log.WithFields(applog.GetAppLogFields(origApp)).Debug("Successfully processed app hydrate queue item")
+ getAppLog(origApp).Debug("Successfully processed app hydrate queue item")
return
}
@@ -1890,7 +1884,7 @@ func currentSourceEqualsSyncedSource(app *appv1.Application) bool {
// Additionally, it returns whether full refresh was requested or not.
// If full refresh is requested then target and live state should be reconciled, else only live state tree should be updated.
func (ctrl *ApplicationController) needRefreshAppStatus(app *appv1.Application, statusRefreshTimeout, statusHardRefreshTimeout time.Duration) (bool, appv1.RefreshType, CompareWith) {
- logCtx := log.WithFields(applog.GetAppLogFields(app))
+ logCtx := getAppLog(app)
var reason string
compareWith := CompareWithLatest
refreshType := appv1.RefreshTypeNormal
@@ -1923,7 +1917,7 @@ func (ctrl *ApplicationController) needRefreshAppStatus(app *appv1.Application,
reason = fmt.Sprintf("comparison expired, requesting hard refresh. reconciledAt: %v, expiry: %v", reconciledAtStr, statusHardRefreshTimeout)
refreshType = appv1.RefreshTypeHard
}
- } else if !reflect.DeepEqual(app.Spec.Destination, app.Status.Sync.ComparedTo.Destination) {
+ } else if !app.Spec.Destination.Equals(app.Status.Sync.ComparedTo.Destination) {
reason = "spec.destination differs"
} else if app.HasChangedManagedNamespaceMetadata() {
reason = "spec.syncPolicy.managedNamespaceMetadata differs"
@@ -1968,7 +1962,7 @@ func (ctrl *ApplicationController) refreshAppConditions(app *appv1.Application)
// normalizeApplication normalizes an application.spec and additionally persists updates if it changed
func (ctrl *ApplicationController) normalizeApplication(orig, app *appv1.Application) {
app.Spec = *argo.NormalizeApplicationSpec(&app.Spec)
- logCtx := log.WithFields(applog.GetAppLogFields(app))
+ logCtx := getAppLog(app)
patch, modified, err := diff.CreateTwoWayMergePatch(orig, app, appv1.Application{})
@@ -1984,7 +1978,7 @@ func (ctrl *ApplicationController) normalizeApplication(orig, app *appv1.Applica
}
}
-func createMergePatch(orig, new any) ([]byte, bool, error) {
+func createMergePatch(orig, new interface{}) ([]byte, bool, error) {
origBytes, err := json.Marshal(orig)
if err != nil {
return nil, false, err
@@ -2001,24 +1995,22 @@ func createMergePatch(orig, new any) ([]byte, bool, error) {
}
// persistAppStatus persists updates to application status. If no changes were made, it is a no-op
-func (ctrl *ApplicationController) persistAppStatus(orig *appv1.Application, newStatus *appv1.ApplicationStatus) (patchDuration time.Duration) {
- logCtx := log.WithFields(applog.GetAppLogFields(orig))
+func (ctrl *ApplicationController) persistAppStatus(orig *appv1.Application, newStatus *appv1.ApplicationStatus) (patchMs time.Duration) {
+ 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(context.TODO(), orig, argo.EventInfo{Reason: argo.EventReasonResourceUpdated, Type: corev1.EventTypeNormal}, message)
+ ctrl.logAppEvent(orig, argo.EventInfo{Reason: argo.EventReasonResourceUpdated, Type: v1.EventTypeNormal}, message, context.TODO())
}
if orig.Status.Health.Status != newStatus.Health.Status {
- // Update the last transition time to now. This should be the ONLY place in code where this is set, because it's
- // the only place that is reliably aware of the previous and updated health statuses.
now := metav1.Now()
newStatus.Health.LastTransitionTime = &now
-
message := fmt.Sprintf("Updated health status: %s -> %s", orig.Status.Health.Status, newStatus.Health.Status)
- ctrl.logAppEvent(context.TODO(), orig, argo.EventInfo{Reason: argo.EventReasonResourceUpdated, Type: corev1.EventTypeNormal}, message)
+ ctrl.logAppEvent(orig, argo.EventInfo{Reason: argo.EventReasonResourceUpdated, Type: v1.EventTypeNormal}, message, context.TODO())
} else {
// make sure the last transition time is the same and populated if the health is the same
newStatus.Health.LastTransitionTime = orig.Status.Health.LastTransitionTime
}
+
var newAnnotations map[string]string
if orig.GetAnnotations() != nil {
newAnnotations = make(map[string]string)
@@ -2042,7 +2034,7 @@ func (ctrl *ApplicationController) persistAppStatus(orig *appv1.Application, new
// calculate time for path call
start := time.Now()
defer func() {
- patchDuration = time.Since(start)
+ patchMs = time.Since(start)
}()
_, err = ctrl.PatchAppWithWriteBack(context.Background(), orig.Name, orig.Namespace, types.MergePatchType, patch, metav1.PatchOptions{})
if err != nil {
@@ -2050,12 +2042,12 @@ func (ctrl *ApplicationController) persistAppStatus(orig *appv1.Application, new
} else {
logCtx.Infof("Update successful")
}
- return patchDuration
+ return patchMs
}
// autoSync will initiate a sync operation for an application configured with automated sync
func (ctrl *ApplicationController) autoSync(app *appv1.Application, syncStatus *appv1.SyncStatus, resources []appv1.ResourceStatus, revisionUpdated bool) (*appv1.ApplicationCondition, time.Duration) {
- logCtx := log.WithFields(applog.GetAppLogFields(app))
+ logCtx := getAppLog(app)
ts := stats.NewTimingStats()
defer func() {
for k, v := range ts.Timings() {
@@ -2064,7 +2056,7 @@ func (ctrl *ApplicationController) autoSync(app *appv1.Application, syncStatus *
logCtx = logCtx.WithField("time_ms", time.Since(ts.StartTime).Milliseconds())
logCtx.Debug("Finished auto sync")
}()
- if app.Spec.SyncPolicy == nil || !app.Spec.SyncPolicy.IsAutomatedSyncEnabled() {
+ if app.Spec.SyncPolicy == nil || app.Spec.SyncPolicy.Automated == nil {
return nil, 0
}
@@ -2183,7 +2175,7 @@ func (ctrl *ApplicationController) autoSync(app *appv1.Application, syncStatus *
ts.AddCheckpoint("set_app_operation_ms")
setOpTime := time.Since(start)
if err != nil {
- if stderrors.Is(err, argo.ErrAnotherOperationInProgress) {
+ if goerrors.Is(err, argo.ErrAnotherOperationInProgress) {
// skipping auto-sync because another operation is in progress and was not noticed due to stale data in informer
// it is safe to skip auto-sync because it is already running
logCtx.Warnf("Failed to initiate auto-sync to %s: %v", desiredCommitSHA, err)
@@ -2192,8 +2184,9 @@ 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
@@ -2203,7 +2196,7 @@ func (ctrl *ApplicationController) autoSync(app *appv1.Application, syncStatus *
target = desiredCommitSHA
}
message := fmt.Sprintf("Initiated automated sync to '%s'", target)
- ctrl.logAppEvent(context.TODO(), app, argo.EventInfo{Reason: argo.EventReasonOperationStarted, Type: corev1.EventTypeNormal}, message)
+ ctrl.logAppEvent(app, argo.EventInfo{Reason: argo.EventReasonOperationStarted, Type: v1.EventTypeNormal}, message, context.TODO())
logCtx.Info(message)
return nil, setOpTime
}
@@ -2220,23 +2213,24 @@ func alreadyAttemptedSync(app *appv1.Application, commitSHA string, commitSHAsMS
return false, ""
}
} else {
- log.WithFields(applog.GetAppLogFields(app)).Debugf("Skipping auto-sync: commitSHA %s has no changes", commitSHA)
+ log.WithField("application", app.Name).Debugf("Skipping auto-sync: commitSHA %s has no changes", commitSHA)
}
} else {
if revisionUpdated {
- log.WithFields(applog.GetAppLogFields(app)).Infof("Executing compare of syncResult.Revision and commitSha because manifest changed: %v", commitSHA)
+ log.WithField("application", app.Name).Infof("Executing compare of syncResult.Revision and commitSha because manifest changed: %v", commitSHA)
if app.Status.OperationState.SyncResult.Revision != commitSHA {
return false, ""
}
} else {
- log.WithFields(applog.GetAppLogFields(app)).Debugf("Skipping auto-sync: commitSHA %s has no changes", commitSHA)
+ log.WithField("application", app.Name).Debugf("Skipping auto-sync: commitSHA %s has no changes", commitSHA)
}
}
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, alreadyAttempted bool) (bool, time.Duration) {
@@ -2285,7 +2279,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 any) bool {
+func (ctrl *ApplicationController) canProcessApp(obj interface{}) bool {
app, ok := obj.(*appv1.Application)
if !ok {
return false
@@ -2299,7 +2293,7 @@ func (ctrl *ApplicationController) canProcessApp(obj any) bool {
if annotations := app.GetAnnotations(); annotations != nil {
if skipVal, ok := annotations[common.AnnotationKeyAppSkipReconcile]; ok {
- logCtx := log.WithFields(applog.GetAppLogFields(app))
+ logCtx := getAppLog(app)
if skipReconcile, err := strconv.ParseBool(skipVal); err == nil {
if skipReconcile {
logCtx.Debugf("Skipping Application reconcile based on annotation %s", common.AnnotationKeyAppSkipReconcile)
@@ -2311,11 +2305,11 @@ func (ctrl *ApplicationController) canProcessApp(obj any) bool {
}
}
- destCluster, err := argo.GetDestinationCluster(context.Background(), app.Spec.Destination, ctrl.db)
+ cluster, err := ctrl.db.GetCluster(context.Background(), app.Spec.Destination.Server)
if err != nil {
return ctrl.clusterSharding.IsManagedCluster(nil)
}
- return ctrl.clusterSharding.IsManagedCluster(destCluster)
+ return ctrl.clusterSharding.IsManagedCluster(cluster)
}
func (ctrl *ApplicationController) newApplicationInformerAndLister() (cache.SharedIndexInformer, applisters.ApplicationLister) {
@@ -2354,7 +2348,7 @@ func (ctrl *ApplicationController) newApplicationInformerAndLister() (cache.Shar
&appv1.Application{},
refreshTimeout,
cache.Indexers{
- cache.NamespaceIndex: func(obj any) ([]string, error) {
+ cache.NamespaceIndex: func(obj interface{}) ([]string, error) {
app, ok := obj.(*appv1.Application)
if ok {
// We only generally work with applications that are in one
@@ -2364,15 +2358,23 @@ func (ctrl *ApplicationController) newApplicationInformerAndLister() (cache.Shar
// log an error.
if _, err := ctrl.getAppProj(app); err != nil {
ctrl.setAppCondition(app, ctrl.projectErrorToCondition(err, app))
- } else if _, err = argo.GetDestinationCluster(context.Background(), app.Spec.Destination, ctrl.db); err != nil {
- ctrl.setAppCondition(app, appv1.ApplicationCondition{Type: appv1.ApplicationConditionInvalidSpecError, Message: err.Error()})
+ } else {
+ // This call to 'ValidateDestination' ensures that the .spec.destination field of all Applications
+ // returned by the informer/lister will have server field set (if not already set) based on the name.
+ // (or, if not found, an error app condition)
+
+ // If the server field is not set, set it based on the cluster name; if the cluster name can't be found,
+ // log an error as an App Condition.
+ if err := argo.ValidateDestination(context.Background(), &app.Spec.Destination, ctrl.db); err != nil {
+ ctrl.setAppCondition(app, appv1.ApplicationCondition{Type: appv1.ApplicationConditionInvalidSpecError, Message: err.Error()})
+ }
}
}
}
return cache.MetaNamespaceIndexFunc(obj)
},
- orphanedIndex: func(obj any) (i []string, e error) {
+ orphanedIndex: func(obj interface{}) (i []string, e error) {
app, ok := obj.(*appv1.Application)
if !ok {
return nil, nil
@@ -2396,7 +2398,7 @@ func (ctrl *ApplicationController) newApplicationInformerAndLister() (cache.Shar
lister := applisters.NewApplicationLister(informer.GetIndexer())
_, err := informer.AddEventHandler(
cache.ResourceEventHandlerFuncs{
- AddFunc: func(obj any) {
+ AddFunc: func(obj interface{}) {
if !ctrl.canProcessApp(obj) {
return
}
@@ -2409,7 +2411,7 @@ func (ctrl *ApplicationController) newApplicationInformerAndLister() (cache.Shar
ctrl.clusterSharding.AddApp(newApp)
}
},
- UpdateFunc: func(old, new any) {
+ UpdateFunc: func(old, new interface{}) {
if !ctrl.canProcessApp(new) {
return
}
@@ -2426,7 +2428,7 @@ func (ctrl *ApplicationController) newApplicationInformerAndLister() (cache.Shar
newApp, newOK := new.(*appv1.Application)
if oldOK && newOK {
if automatedSyncEnabled(oldApp, newApp) {
- log.WithFields(applog.GetAppLogFields(newApp)).Info("Enabled automated sync")
+ getAppLog(newApp).Info("Enabled automated sync")
compareWith = CompareWithLatest.Pointer()
}
if ctrl.statusRefreshJitter != 0 && oldApp.ResourceVersion == newApp.ResourceVersion {
@@ -2445,7 +2447,7 @@ func (ctrl *ApplicationController) newApplicationInformerAndLister() (cache.Shar
}
ctrl.clusterSharding.UpdateApp(newApp)
},
- DeleteFunc: func(obj any) {
+ DeleteFunc: func(obj interface{}) {
if !ctrl.canProcessApp(obj) {
return
}
@@ -2471,7 +2473,7 @@ func (ctrl *ApplicationController) newApplicationInformerAndLister() (cache.Shar
func (ctrl *ApplicationController) projectErrorToCondition(err error, app *appv1.Application) appv1.ApplicationCondition {
var condition appv1.ApplicationCondition
- if apierrors.IsNotFound(err) {
+ if apierr.IsNotFound(err) {
condition = appv1.ApplicationCondition{
Type: appv1.ApplicationConditionInvalidSpecError,
Message: fmt.Sprintf("Application referencing project %s which does not exist", app.Spec.Project),
@@ -2496,14 +2498,14 @@ func isOperationInProgress(app *appv1.Application) bool {
func automatedSyncEnabled(oldApp *appv1.Application, newApp *appv1.Application) bool {
oldEnabled := false
oldSelfHealEnabled := false
- if oldApp.Spec.SyncPolicy != nil && oldApp.Spec.SyncPolicy.IsAutomatedSyncEnabled() {
+ if oldApp.Spec.SyncPolicy != nil && oldApp.Spec.SyncPolicy.Automated != nil {
oldEnabled = true
oldSelfHealEnabled = oldApp.Spec.SyncPolicy.Automated.SelfHeal
}
newEnabled := false
newSelfHealEnabled := false
- if newApp.Spec.SyncPolicy != nil && newApp.Spec.SyncPolicy.IsAutomatedSyncEnabled() {
+ if newApp.Spec.SyncPolicy != nil && newApp.Spec.SyncPolicy.Automated != nil {
newEnabled = true
newSelfHealEnabled = newApp.Spec.SyncPolicy.Automated.SelfHeal
}
@@ -2526,8 +2528,9 @@ 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 {
@@ -2556,8 +2559,8 @@ func (ctrl *ApplicationController) getAppList(options metav1.ListOptions) (*appv
return appList, nil
}
-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)
+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)
ctrl.auditLogger.LogAppEvent(a, eventInfo, message, "", eventLabels)
}
diff --git a/controller/appcontroller_test.go b/controller/appcontroller_test.go
index 8185b54628..9efe356245 100644
--- a/controller/appcontroller_test.go
+++ b/controller/appcontroller_test.go
@@ -19,18 +19,18 @@ import (
"k8s.io/client-go/rest"
"k8s.io/utils/ptr"
- "github.com/argoproj/argo-cd/v3/common"
- statecache "github.com/argoproj/argo-cd/v3/controller/cache"
- "github.com/argoproj/argo-cd/v3/controller/sharding"
+ "github.com/argoproj/argo-cd/v2/common"
+ statecache "github.com/argoproj/argo-cd/v2/controller/cache"
+ "github.com/argoproj/argo-cd/v2/controller/sharding"
"github.com/argoproj/gitops-engine/pkg/cache/mocks"
synccommon "github.com/argoproj/gitops-engine/pkg/sync/common"
"github.com/argoproj/gitops-engine/pkg/utils/kube"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
- appsv1 "k8s.io/api/apps/v1"
+ v1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
- apierrors "k8s.io/apimachinery/pkg/api/errors"
+ apierr "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"
@@ -40,21 +40,20 @@ import (
"k8s.io/client-go/tools/cache"
"sigs.k8s.io/yaml"
- dbmocks "github.com/argoproj/argo-cd/v3/util/db/mocks"
+ dbmocks "github.com/argoproj/argo-cd/v2/util/db/mocks"
- mockcommitclient "github.com/argoproj/argo-cd/v3/commitserver/apiclient/mocks"
- mockstatecache "github.com/argoproj/argo-cd/v3/controller/cache/mocks"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- appclientset "github.com/argoproj/argo-cd/v3/pkg/client/clientset/versioned/fake"
- "github.com/argoproj/argo-cd/v3/reposerver/apiclient"
- mockrepoclient "github.com/argoproj/argo-cd/v3/reposerver/apiclient/mocks"
- "github.com/argoproj/argo-cd/v3/test"
- "github.com/argoproj/argo-cd/v3/util/argo"
- "github.com/argoproj/argo-cd/v3/util/argo/normalizers"
- cacheutil "github.com/argoproj/argo-cd/v3/util/cache"
- appstatecache "github.com/argoproj/argo-cd/v3/util/cache/appstate"
- "github.com/argoproj/argo-cd/v3/util/settings"
- utilTest "github.com/argoproj/argo-cd/v3/util/test"
+ mockcommitclient "github.com/argoproj/argo-cd/v2/commitserver/apiclient/mocks"
+ mockstatecache "github.com/argoproj/argo-cd/v2/controller/cache/mocks"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+ appclientset "github.com/argoproj/argo-cd/v2/pkg/client/clientset/versioned/fake"
+ "github.com/argoproj/argo-cd/v2/reposerver/apiclient"
+ mockrepoclient "github.com/argoproj/argo-cd/v2/reposerver/apiclient/mocks"
+ "github.com/argoproj/argo-cd/v2/test"
+ "github.com/argoproj/argo-cd/v2/util/argo"
+ "github.com/argoproj/argo-cd/v2/util/argo/normalizers"
+ 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/settings"
)
var testEnableEventList []string = argo.DefaultEnableEventList()
@@ -179,7 +178,6 @@ func newFakeControllerWithResync(data *fakeData, appResyncPeriod time.Duration,
data.metricsCacheExpiration,
[]string{},
[]string{},
- []string{},
0,
true,
nil,
@@ -211,7 +209,7 @@ func newFakeControllerWithResync(data *fakeData, appResyncPeriod time.Duration,
ctrl.appStateManager.(*appStateManager).liveStateCache = &mockStateCache
ctrl.stateCache = &mockStateCache
mockStateCache.On("IsNamespaced", mock.Anything, mock.Anything).Return(true, nil)
- mockStateCache.On("GetManagedLiveObjs", mock.Anything, mock.Anything, mock.Anything).Return(data.managedLiveObjs, nil)
+ mockStateCache.On("GetManagedLiveObjs", mock.Anything, mock.Anything).Return(data.managedLiveObjs, nil)
mockStateCache.On("GetVersionsInfo", mock.Anything).Return("v1.2.3", nil, nil)
response := make(map[kube.ResourceKey]v1alpha1.ResourceNode)
for k, v := range data.namespacedResources {
@@ -518,7 +516,7 @@ func newFakeMultiSourceApp() *v1alpha1.Application {
func createFakeAppWithHealthAndTime(testApp string, status health.HealthStatusCode, timestamp metav1.Time) *v1alpha1.Application {
app := createFakeApp(testApp)
- app.Status.Health = v1alpha1.AppHealthStatus{
+ app.Status.Health = v1alpha1.HealthStatus{
Status: status,
LastTransitionTime: ×tamp,
}
@@ -542,8 +540,8 @@ func createFakeApp(testApp string) *v1alpha1.Application {
return &app
}
-func newFakeCM() map[string]any {
- var cm map[string]any
+func newFakeCM() map[string]interface{} {
+ var cm map[string]interface{}
err := yaml.Unmarshal([]byte(fakeStrayResource), &cm)
if err != nil {
panic(err)
@@ -551,8 +549,8 @@ func newFakeCM() map[string]any {
return cm
}
-func newFakePostDeleteHook() map[string]any {
- var hook map[string]any
+func newFakePostDeleteHook() map[string]interface{} {
+ var hook map[string]interface{}
err := yaml.Unmarshal([]byte(fakePostDeleteHook), &hook)
if err != nil {
panic(err)
@@ -560,8 +558,8 @@ func newFakePostDeleteHook() map[string]any {
return hook
}
-func newFakeRoleBinding() map[string]any {
- var roleBinding map[string]any
+func newFakeRoleBinding() map[string]interface{} {
+ var roleBinding map[string]interface{}
err := yaml.Unmarshal([]byte(fakeRoleBinding), &roleBinding)
if err != nil {
panic(err)
@@ -569,8 +567,8 @@ func newFakeRoleBinding() map[string]any {
return roleBinding
}
-func newFakeRole() map[string]any {
- var role map[string]any
+func newFakeRole() map[string]interface{} {
+ var role map[string]interface{}
err := yaml.Unmarshal([]byte(fakeRole), &role)
if err != nil {
panic(err)
@@ -578,8 +576,8 @@ func newFakeRole() map[string]any {
return role
}
-func newFakeServiceAccount() map[string]any {
- var serviceAccount map[string]any
+func newFakeServiceAccount() map[string]interface{} {
+ var serviceAccount map[string]interface{}
err := yaml.Unmarshal([]byte(fakeServiceAccount), &serviceAccount)
if err != nil {
panic(err)
@@ -596,25 +594,7 @@ func TestAutoSync(t *testing.T) {
}
cond, _ := ctrl.autoSync(app, &syncStatus, []v1alpha1.ResourceStatus{{Name: "guestbook", Kind: kube.DeploymentKind, Status: v1alpha1.SyncStatusCodeOutOfSync}}, true)
assert.Nil(t, cond)
- app, err := ctrl.applicationClientset.ArgoprojV1alpha1().Applications(test.FakeArgoCDNamespace).Get(t.Context(), "my-app", metav1.GetOptions{})
- require.NoError(t, err)
- assert.NotNil(t, app.Operation)
- assert.NotNil(t, app.Operation.Sync)
- assert.False(t, app.Operation.Sync.Prune)
-}
-
-func TestAutoSyncEnabledSetToTrue(t *testing.T) {
- app := newFakeApp()
- enable := true
- app.Spec.SyncPolicy.Automated = &v1alpha1.SyncPolicyAutomated{Enabled: &enable}
- ctrl := newFakeController(&fakeData{apps: []runtime.Object{app}}, nil)
- syncStatus := v1alpha1.SyncStatus{
- Status: v1alpha1.SyncStatusCodeOutOfSync,
- Revision: "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
- }
- cond, _ := ctrl.autoSync(app, &syncStatus, []v1alpha1.ResourceStatus{{Name: "guestbook", Kind: kube.DeploymentKind, Status: v1alpha1.SyncStatusCodeOutOfSync}}, true)
- assert.Nil(t, cond)
- app, err := ctrl.applicationClientset.ArgoprojV1alpha1().Applications(test.FakeArgoCDNamespace).Get(t.Context(), "my-app", metav1.GetOptions{})
+ app, err := ctrl.applicationClientset.ArgoprojV1alpha1().Applications(test.FakeArgoCDNamespace).Get(context.Background(), "my-app", metav1.GetOptions{})
require.NoError(t, err)
assert.NotNil(t, app.Operation)
assert.NotNil(t, app.Operation.Sync)
@@ -635,7 +615,7 @@ func TestMultiSourceSelfHeal(t *testing.T) {
}
cond, _ := ctrl.autoSync(app, &syncStatus, []v1alpha1.ResourceStatus{{Name: "guestbook-1", Kind: kube.DeploymentKind, Status: v1alpha1.SyncStatusCodeOutOfSync}}, true)
assert.Nil(t, cond)
- app, err := ctrl.applicationClientset.ArgoprojV1alpha1().Applications(test.FakeArgoCDNamespace).Get(t.Context(), "my-app", metav1.GetOptions{})
+ app, err := ctrl.applicationClientset.ArgoprojV1alpha1().Applications(test.FakeArgoCDNamespace).Get(context.Background(), "my-app", metav1.GetOptions{})
require.NoError(t, err)
assert.Nil(t, app.Operation)
})
@@ -651,7 +631,7 @@ func TestMultiSourceSelfHeal(t *testing.T) {
}
cond, _ := ctrl.autoSync(app, &syncStatus, []v1alpha1.ResourceStatus{{Name: "guestbook-1", Kind: kube.DeploymentKind, Status: v1alpha1.SyncStatusCodeOutOfSync}}, true)
assert.Nil(t, cond)
- app, err := ctrl.applicationClientset.ArgoprojV1alpha1().Applications(test.FakeArgoCDNamespace).Get(t.Context(), "my-app", metav1.GetOptions{})
+ app, err := ctrl.applicationClientset.ArgoprojV1alpha1().Applications(test.FakeArgoCDNamespace).Get(context.Background(), "my-app", metav1.GetOptions{})
require.NoError(t, err)
assert.NotNil(t, app.Operation)
})
@@ -694,7 +674,7 @@ func TestSkipAutoSync(t *testing.T) {
}
cond, _ := ctrl.autoSync(app, &syncStatus, []v1alpha1.ResourceStatus{}, true)
assert.Nil(t, cond)
- app, err := ctrl.applicationClientset.ArgoprojV1alpha1().Applications(test.FakeArgoCDNamespace).Get(t.Context(), "my-app", metav1.GetOptions{})
+ app, err := ctrl.applicationClientset.ArgoprojV1alpha1().Applications(test.FakeArgoCDNamespace).Get(context.Background(), "my-app", metav1.GetOptions{})
require.NoError(t, err)
assert.Nil(t, app.Operation)
})
@@ -709,7 +689,7 @@ func TestSkipAutoSync(t *testing.T) {
}
cond, _ := ctrl.autoSync(app, &syncStatus, []v1alpha1.ResourceStatus{}, true)
assert.Nil(t, cond)
- app, err := ctrl.applicationClientset.ArgoprojV1alpha1().Applications(test.FakeArgoCDNamespace).Get(t.Context(), "my-app", metav1.GetOptions{})
+ app, err := ctrl.applicationClientset.ArgoprojV1alpha1().Applications(test.FakeArgoCDNamespace).Get(context.Background(), "my-app", metav1.GetOptions{})
require.NoError(t, err)
assert.Nil(t, app.Operation)
})
@@ -725,24 +705,7 @@ func TestSkipAutoSync(t *testing.T) {
}
cond, _ := ctrl.autoSync(app, &syncStatus, []v1alpha1.ResourceStatus{}, true)
assert.Nil(t, cond)
- app, err := ctrl.applicationClientset.ArgoprojV1alpha1().Applications(test.FakeArgoCDNamespace).Get(t.Context(), "my-app", metav1.GetOptions{})
- require.NoError(t, err)
- assert.Nil(t, app.Operation)
- })
-
- // Verify we skip when auto-sync is disabled
- t.Run("AutoSyncEnableFieldIsSetFalse", func(t *testing.T) {
- app := newFakeApp()
- enable := false
- app.Spec.SyncPolicy.Automated = &v1alpha1.SyncPolicyAutomated{Enabled: &enable}
- ctrl := newFakeController(&fakeData{apps: []runtime.Object{app}}, nil)
- syncStatus := v1alpha1.SyncStatus{
- Status: v1alpha1.SyncStatusCodeOutOfSync,
- Revision: "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
- }
- cond, _ := ctrl.autoSync(app, &syncStatus, []v1alpha1.ResourceStatus{}, true)
- assert.Nil(t, cond)
- app, err := ctrl.applicationClientset.ArgoprojV1alpha1().Applications(test.FakeArgoCDNamespace).Get(t.Context(), "my-app", metav1.GetOptions{})
+ app, err := ctrl.applicationClientset.ArgoprojV1alpha1().Applications(test.FakeArgoCDNamespace).Get(context.Background(), "my-app", metav1.GetOptions{})
require.NoError(t, err)
assert.Nil(t, app.Operation)
})
@@ -759,7 +722,7 @@ func TestSkipAutoSync(t *testing.T) {
}
cond, _ := ctrl.autoSync(app, &syncStatus, []v1alpha1.ResourceStatus{}, true)
assert.Nil(t, cond)
- app, err := ctrl.applicationClientset.ArgoprojV1alpha1().Applications(test.FakeArgoCDNamespace).Get(t.Context(), "my-app", metav1.GetOptions{})
+ app, err := ctrl.applicationClientset.ArgoprojV1alpha1().Applications(test.FakeArgoCDNamespace).Get(context.Background(), "my-app", metav1.GetOptions{})
require.NoError(t, err)
assert.Nil(t, app.Operation)
})
@@ -785,7 +748,7 @@ func TestSkipAutoSync(t *testing.T) {
}
cond, _ := ctrl.autoSync(app, &syncStatus, []v1alpha1.ResourceStatus{{Name: "guestbook", Kind: kube.DeploymentKind, Status: v1alpha1.SyncStatusCodeOutOfSync}}, true)
assert.NotNil(t, cond)
- app, err := ctrl.applicationClientset.ArgoprojV1alpha1().Applications(test.FakeArgoCDNamespace).Get(t.Context(), "my-app", metav1.GetOptions{})
+ app, err := ctrl.applicationClientset.ArgoprojV1alpha1().Applications(test.FakeArgoCDNamespace).Get(context.Background(), "my-app", metav1.GetOptions{})
require.NoError(t, err)
assert.Nil(t, app.Operation)
})
@@ -801,7 +764,7 @@ func TestSkipAutoSync(t *testing.T) {
{Name: "guestbook", Kind: kube.DeploymentKind, Status: v1alpha1.SyncStatusCodeOutOfSync, RequiresPruning: true},
}, true)
assert.Nil(t, cond)
- app, err := ctrl.applicationClientset.ArgoprojV1alpha1().Applications(test.FakeArgoCDNamespace).Get(t.Context(), "my-app", metav1.GetOptions{})
+ app, err := ctrl.applicationClientset.ArgoprojV1alpha1().Applications(test.FakeArgoCDNamespace).Get(context.Background(), "my-app", metav1.GetOptions{})
require.NoError(t, err)
assert.Nil(t, app.Operation)
})
@@ -837,7 +800,7 @@ func TestAutoSyncIndicateError(t *testing.T) {
}
cond, _ := ctrl.autoSync(app, &syncStatus, []v1alpha1.ResourceStatus{{Name: "guestbook", Kind: kube.DeploymentKind, Status: v1alpha1.SyncStatusCodeOutOfSync}}, true)
assert.NotNil(t, cond)
- app, err := ctrl.applicationClientset.ArgoprojV1alpha1().Applications(test.FakeArgoCDNamespace).Get(t.Context(), "my-app", metav1.GetOptions{})
+ app, err := ctrl.applicationClientset.ArgoprojV1alpha1().Applications(test.FakeArgoCDNamespace).Get(context.Background(), "my-app", metav1.GetOptions{})
require.NoError(t, err)
assert.Nil(t, app.Operation)
}
@@ -880,7 +843,7 @@ func TestAutoSyncParameterOverrides(t *testing.T) {
}
cond, _ := ctrl.autoSync(app, &syncStatus, []v1alpha1.ResourceStatus{{Name: "guestbook", Kind: kube.DeploymentKind, Status: v1alpha1.SyncStatusCodeOutOfSync}}, true)
assert.Nil(t, cond)
- app, err := ctrl.applicationClientset.ArgoprojV1alpha1().Applications(test.FakeArgoCDNamespace).Get(t.Context(), "my-app", metav1.GetOptions{})
+ app, err := ctrl.applicationClientset.ArgoprojV1alpha1().Applications(test.FakeArgoCDNamespace).Get(context.Background(), "my-app", metav1.GetOptions{})
require.NoError(t, err)
assert.NotNil(t, app.Operation)
}
@@ -918,11 +881,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(_ kubetesting.Action) (handled bool, ret runtime.Object, err error) {
+ fakeAppCs.AddReactor("patch", "*", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) {
patched = true
return true, &v1alpha1.Application{}, nil
})
- err := ctrl.finalizeApplicationDeletion(app, func(_ string) ([]*v1alpha1.Cluster, error) {
+ err := ctrl.finalizeApplicationDeletion(app, func(project string) ([]*v1alpha1.Cluster, error) {
return []*v1alpha1.Cluster{}, nil
})
require.NoError(t, err)
@@ -970,16 +933,16 @@ 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(_ kubetesting.Action) (handled bool, ret runtime.Object, err error) {
+ fakeAppCs.AddReactor("patch", "*", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) {
patched = true
return true, &v1alpha1.Application{}, nil
})
- err := ctrl.finalizeApplicationDeletion(app, func(_ string) ([]*v1alpha1.Cluster, error) {
+ err := ctrl.finalizeApplicationDeletion(app, func(project string) ([]*v1alpha1.Cluster, error) {
return []*v1alpha1.Cluster{}, nil
})
require.NoError(t, err)
assert.True(t, patched)
- objsMap, err := ctrl.stateCache.GetManagedLiveObjs(&v1alpha1.Cluster{Server: "test", Name: "test"}, app, []*unstructured.Unstructured{})
+ objsMap, err := ctrl.stateCache.GetManagedLiveObjs(app, []*unstructured.Unstructured{})
if err != nil {
require.NoError(t, err)
}
@@ -1004,11 +967,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(_ kubetesting.Action) (handled bool, ret runtime.Object, err error) {
+ fakeAppCs.AddReactor("patch", "*", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) {
patched = true
return true, &v1alpha1.Application{}, nil
})
- err := ctrl.finalizeApplicationDeletion(app, func(_ string) ([]*v1alpha1.Cluster, error) {
+ err := ctrl.finalizeApplicationDeletion(app, func(project string) ([]*v1alpha1.Cluster, error) {
return []*v1alpha1.Cluster{}, nil
})
require.NoError(t, err)
@@ -1032,7 +995,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(_ string) ([]*v1alpha1.Cluster, error) {
+ err := ctrl.finalizeApplicationDeletion(app, func(project string) ([]*v1alpha1.Cluster, error) {
return []*v1alpha1.Cluster{}, nil
})
require.NoError(t, err)
@@ -1071,11 +1034,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(_ kubetesting.Action) (handled bool, ret runtime.Object, err error) {
+ fakeAppCs.AddReactor("patch", "*", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) {
patched = true
return true, &v1alpha1.Application{}, nil
})
- err := ctrl.finalizeApplicationDeletion(app, func(_ string) ([]*v1alpha1.Cluster, error) {
+ err := ctrl.finalizeApplicationDeletion(app, func(project string) ([]*v1alpha1.Cluster, error) {
return []*v1alpha1.Cluster{}, nil
})
require.NoError(t, err)
@@ -1091,8 +1054,8 @@ func TestFinalizeAppDeletion(t *testing.T) {
app.SetPostDeleteFinalizer()
app.Spec.Destination.Namespace = test.FakeArgoCDNamespace
liveHook := &unstructured.Unstructured{Object: newFakePostDeleteHook()}
- conditions := []any{
- map[string]any{
+ conditions := []interface{}{
+ map[string]interface{}{
"type": "Complete",
"status": "True",
},
@@ -1115,11 +1078,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(_ kubetesting.Action) (handled bool, ret runtime.Object, err error) {
+ fakeAppCs.AddReactor("patch", "*", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) {
patched = true
return true, &v1alpha1.Application{}, nil
})
- err := ctrl.finalizeApplicationDeletion(app, func(_ string) ([]*v1alpha1.Cluster, error) {
+ err := ctrl.finalizeApplicationDeletion(app, func(project string) ([]*v1alpha1.Cluster, error) {
return []*v1alpha1.Cluster{}, nil
})
require.NoError(t, err)
@@ -1135,8 +1098,8 @@ func TestFinalizeAppDeletion(t *testing.T) {
liveRole := &unstructured.Unstructured{Object: newFakeRole()}
liveServiceAccount := &unstructured.Unstructured{Object: newFakeServiceAccount()}
liveHook := &unstructured.Unstructured{Object: newFakePostDeleteHook()}
- conditions := []any{
- map[string]any{
+ conditions := []interface{}{
+ map[string]interface{}{
"type": "Complete",
"status": "True",
},
@@ -1162,11 +1125,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(_ kubetesting.Action) (handled bool, ret runtime.Object, err error) {
+ fakeAppCs.AddReactor("patch", "*", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) {
patched = true
return true, &v1alpha1.Application{}, nil
})
- err := ctrl.finalizeApplicationDeletion(app, func(_ string) ([]*v1alpha1.Cluster, error) {
+ err := ctrl.finalizeApplicationDeletion(app, func(project string) ([]*v1alpha1.Cluster, error) {
return []*v1alpha1.Cluster{}, nil
})
require.NoError(t, err)
@@ -1326,7 +1289,7 @@ func TestGetResourceTree_HasOrphanedResources(t *testing.T) {
kube.NewResourceKey("apps", "Deployment", "default", "deploy2"): {ResourceNode: orphanedDeploy2},
},
}, nil)
- tree, err := ctrl.getResourceTree(&v1alpha1.Cluster{Server: "https://localhost:6443", Name: "fake-cluster"}, app, []*v1alpha1.ResourceDiff{{
+ tree, err := ctrl.getResourceTree(app, []*v1alpha1.ResourceDiff{{
Namespace: "default",
Name: "nginx-deployment",
Kind: "Deployment",
@@ -1345,16 +1308,29 @@ func TestSetOperationStateOnDeletedApp(t *testing.T) {
fakeAppCs := ctrl.applicationClientset.(*appclientset.Clientset)
fakeAppCs.ReactionChain = nil
patched := false
- fakeAppCs.AddReactor("patch", "*", func(_ kubetesting.Action) (handled bool, ret runtime.Object, err error) {
+ fakeAppCs.AddReactor("patch", "*", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) {
patched = true
- return true, &v1alpha1.Application{}, apierrors.NewNotFound(schema.GroupResource{}, "my-app")
+ return true, &v1alpha1.Application{}, apierr.NewNotFound(schema.GroupResource{}, "my-app")
})
ctrl.setOperationState(newFakeApp(), &v1alpha1.OperationState{Phase: synccommon.OperationSucceeded})
assert.True(t, patched)
}
+type logHook struct {
+ entries []logrus.Entry
+}
+
+func (h *logHook) Levels() []logrus.Level {
+ return []logrus.Level{logrus.WarnLevel}
+}
+
+func (h *logHook) Fire(entry *logrus.Entry) error {
+ h.entries = append(h.entries, *entry)
+ return nil
+}
+
func TestSetOperationStateLogRetries(t *testing.T) {
- hook := utilTest.LogHook{}
+ hook := logHook{}
logrus.AddHook(&hook)
t.Cleanup(func() {
logrus.StandardLogger().ReplaceHooks(logrus.LevelHooks{})
@@ -1363,7 +1339,7 @@ func TestSetOperationStateLogRetries(t *testing.T) {
fakeAppCs := ctrl.applicationClientset.(*appclientset.Clientset)
fakeAppCs.ReactionChain = nil
patched := false
- fakeAppCs.AddReactor("patch", "*", func(_ kubetesting.Action) (handled bool, ret runtime.Object, err error) {
+ fakeAppCs.AddReactor("patch", "*", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) {
if !patched {
patched = true
return true, &v1alpha1.Application{}, errors.New("fake error")
@@ -1372,7 +1348,7 @@ func TestSetOperationStateLogRetries(t *testing.T) {
})
ctrl.setOperationState(newFakeApp(), &v1alpha1.OperationState{Phase: synccommon.OperationSucceeded})
assert.True(t, patched)
- assert.Contains(t, hook.Entries[0].Message, "fake error")
+ assert.Contains(t, hook.entries[0].Message, "fake error")
}
func TestNeedRefreshAppStatus(t *testing.T) {
@@ -1698,7 +1674,7 @@ func TestUpdateReconciledAt(t *testing.T) {
key, _ := cache.MetaNamespaceKeyFunc(app)
fakeAppCs := ctrl.applicationClientset.(*appclientset.Clientset)
fakeAppCs.ReactionChain = nil
- receivedPatch := map[string]any{}
+ receivedPatch := map[string]interface{}{}
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))
@@ -1707,7 +1683,7 @@ func TestUpdateReconciledAt(t *testing.T) {
})
t.Run("UpdatedOnFullReconciliation", func(t *testing.T) {
- receivedPatch = map[string]any{}
+ receivedPatch = map[string]interface{}{}
ctrl.requestAppRefresh(app.Name, CompareWithLatest.Pointer(), nil)
ctrl.appRefreshQueue.AddRateLimited(key)
@@ -1723,7 +1699,7 @@ func TestUpdateReconciledAt(t *testing.T) {
})
t.Run("NotUpdatedOnPartialReconciliation", func(t *testing.T) {
- receivedPatch = map[string]any{}
+ receivedPatch = map[string]interface{}{}
ctrl.appRefreshQueue.AddRateLimited(key)
ctrl.requestAppRefresh(app.Name, CompareWithRecent.Pointer(), nil)
@@ -1740,7 +1716,7 @@ func TestUpdateReconciledAt(t *testing.T) {
}
func TestUpdateHealthStatusTransitionTime(t *testing.T) {
- deployment := kube.MustToUnstructured(&appsv1.Deployment{
+ deployment := kube.MustToUnstructured(&v1.Deployment{
TypeMeta: metav1.TypeMeta{
APIVersion: "apps/v1",
Kind: "Deployment",
@@ -1842,7 +1818,7 @@ apps/Deployment:
func TestUpdateHealthStatusProgression(t *testing.T) {
app := newFakeAppWithHealthAndTime(health.HealthStatusDegraded, testTimestamp)
- deployment := kube.MustToUnstructured(&appsv1.Deployment{
+ deployment := kube.MustToUnstructured(&v1.Deployment{
TypeMeta: metav1.TypeMeta{
APIVersion: "apps/v1",
Kind: "Deployment",
@@ -1851,7 +1827,7 @@ func TestUpdateHealthStatusProgression(t *testing.T) {
Name: "demo",
Namespace: "default",
},
- Status: appsv1.DeploymentStatus{
+ Status: v1.DeploymentStatus{
ObservedGeneration: 0,
},
})
@@ -1862,7 +1838,7 @@ apps/Deployment:
hs = {}
hs.status = ""
hs.message = ""
-
+
if obj.metadata ~= nil then
if obj.metadata.labels ~= nil then
current_status = obj.metadata.labels["status"]
@@ -1979,7 +1955,7 @@ func TestFinalizeProjectDeletion_HasApplications(t *testing.T) {
fakeAppCs := ctrl.applicationClientset.(*appclientset.Clientset)
patched := false
- fakeAppCs.PrependReactor("patch", "*", func(_ kubetesting.Action) (handled bool, ret runtime.Object, err error) {
+ fakeAppCs.PrependReactor("patch", "*", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) {
patched = true
return true, &v1alpha1.Application{}, nil
})
@@ -1994,7 +1970,7 @@ func TestFinalizeProjectDeletion_DoesNotHaveApplications(t *testing.T) {
ctrl := newFakeController(&fakeData{apps: []runtime.Object{&defaultProj}}, nil)
fakeAppCs := ctrl.applicationClientset.(*appclientset.Clientset)
- receivedPatch := map[string]any{}
+ receivedPatch := map[string]interface{}{}
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))
@@ -2004,8 +1980,8 @@ func TestFinalizeProjectDeletion_DoesNotHaveApplications(t *testing.T) {
err := ctrl.finalizeProjectDeletion(proj)
require.NoError(t, err)
- assert.Equal(t, map[string]any{
- "metadata": map[string]any{
+ assert.Equal(t, map[string]interface{}{
+ "metadata": map[string]interface{}{
"finalizers": nil,
},
}, receivedPatch)
@@ -2019,7 +1995,7 @@ func TestProcessRequestedAppOperation_FailedNoRetries(t *testing.T) {
}
ctrl := newFakeController(&fakeData{apps: []runtime.Object{app}}, nil)
fakeAppCs := ctrl.applicationClientset.(*appclientset.Clientset)
- receivedPatch := map[string]any{}
+ receivedPatch := map[string]interface{}{}
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))
@@ -2044,7 +2020,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]any{}
+ receivedPatch := map[string]interface{}{}
func() {
fakeAppCs.Lock()
defer fakeAppCs.Unlock()
@@ -2073,7 +2049,7 @@ func TestProcessRequestedAppOperation_FailedHasRetries(t *testing.T) {
}
ctrl := newFakeController(&fakeData{apps: []runtime.Object{app}}, nil)
fakeAppCs := ctrl.applicationClientset.(*appclientset.Clientset)
- receivedPatch := map[string]any{}
+ receivedPatch := map[string]interface{}{}
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))
@@ -2086,7 +2062,7 @@ func TestProcessRequestedAppOperation_FailedHasRetries(t *testing.T) {
phase, _, _ := unstructured.NestedString(receivedPatch, "status", "operationState", "phase")
assert.Equal(t, string(synccommon.OperationRunning), phase)
message, _, _ := unstructured.NestedString(receivedPatch, "status", "operationState", "message")
- assert.Contains(t, message, "Retrying attempt #1")
+ assert.Contains(t, message, "due to application controller sync timeout. Retrying attempt #1")
retryCount, _, _ := unstructured.NestedFloat64(receivedPatch, "status", "operationState", "retryCount")
assert.InEpsilon(t, float64(1), retryCount, 0.0001)
}
@@ -2116,7 +2092,7 @@ func TestProcessRequestedAppOperation_RunningPreviouslyFailed(t *testing.T) {
}
ctrl := newFakeController(data, nil)
fakeAppCs := ctrl.applicationClientset.(*appclientset.Clientset)
- receivedPatch := map[string]any{}
+ receivedPatch := map[string]interface{}{}
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))
@@ -2149,7 +2125,7 @@ func TestProcessRequestedAppOperation_HasRetriesTerminated(t *testing.T) {
}
ctrl := newFakeController(data, nil)
fakeAppCs := ctrl.applicationClientset.(*appclientset.Clientset)
- receivedPatch := map[string]any{}
+ receivedPatch := map[string]interface{}{}
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))
@@ -2176,7 +2152,7 @@ func TestProcessRequestedAppOperation_Successful(t *testing.T) {
}},
}, nil)
fakeAppCs := ctrl.applicationClientset.(*appclientset.Clientset)
- receivedPatch := map[string]any{}
+ receivedPatch := map[string]interface{}{}
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))
@@ -2234,7 +2210,7 @@ func TestGetAppHosts(t *testing.T) {
})).Return(nil)
ctrl.stateCache = mockStateCache
- hosts, err := ctrl.getAppHosts(&v1alpha1.Cluster{Server: "test", Name: "test"}, app, []v1alpha1.ResourceNode{{
+ hosts, err := ctrl.getAppHosts(app, []v1alpha1.ResourceNode{{
ResourceRef: v1alpha1.ResourceRef{Name: "pod1", Namespace: "default", Kind: kube.PodKind},
Info: []v1alpha1.InfoItem{{
Name: "Host",
@@ -2319,7 +2295,7 @@ func Test_canProcessAppSkipReconcileAnnotation(t *testing.T) {
ctrl := newFakeController(&fakeData{}, nil)
tests := []struct {
name string
- input any
+ input interface{}
expected bool
}{
{"No skip reconcile annotation", newFakeApp(), true},
@@ -2368,7 +2344,7 @@ func TestAddControllerNamespace(t *testing.T) {
ctrl.processAppRefreshQueueItem()
- updatedApp, err := ctrl.applicationClientset.ArgoprojV1alpha1().Applications(ctrl.namespace).Get(t.Context(), app.Name, metav1.GetOptions{})
+ updatedApp, err := ctrl.applicationClientset.ArgoprojV1alpha1().Applications(ctrl.namespace).Get(context.Background(), app.Name, metav1.GetOptions{})
require.NoError(t, err)
assert.Equal(t, test.FakeArgoCDNamespace, updatedApp.Status.ControllerNamespace)
})
@@ -2376,7 +2352,7 @@ func TestAddControllerNamespace(t *testing.T) {
appNamespace := "app-namespace"
app := newFakeApp()
- app.Namespace = appNamespace
+ app.ObjectMeta.Namespace = appNamespace
proj := defaultProj
proj.Spec.SourceNamespaces = []string{appNamespace}
ctrl := newFakeController(&fakeData{
@@ -2387,7 +2363,7 @@ func TestAddControllerNamespace(t *testing.T) {
ctrl.processAppRefreshQueueItem()
- updatedApp, err := ctrl.applicationClientset.ArgoprojV1alpha1().Applications(appNamespace).Get(t.Context(), app.Name, metav1.GetOptions{})
+ updatedApp, err := ctrl.applicationClientset.ArgoprojV1alpha1().Applications(appNamespace).Get(context.Background(), app.Name, metav1.GetOptions{})
require.NoError(t, err)
assert.Equal(t, test.FakeArgoCDNamespace, updatedApp.Status.ControllerNamespace)
})
@@ -2399,7 +2375,7 @@ func TestHelmValuesObjectHasReplaceStrategy(t *testing.T) {
Source: v1alpha1.ApplicationSource{
Helm: &v1alpha1.ApplicationSourceHelm{
ValuesObject: &runtime.RawExtension{
- Object: &unstructured.Unstructured{Object: map[string]any{"key": []string{"value"}}},
+ Object: &unstructured.Unstructured{Object: map[string]interface{}{"key": []string{"value"}}},
},
},
},
@@ -2411,7 +2387,7 @@ func TestHelmValuesObjectHasReplaceStrategy(t *testing.T) {
Source: v1alpha1.ApplicationSource{
Helm: &v1alpha1.ApplicationSourceHelm{
ValuesObject: &runtime.RawExtension{
- Object: &unstructured.Unstructured{Object: map[string]any{"key": []string{"value-modified1"}}},
+ Object: &unstructured.Unstructured{Object: map[string]interface{}{"key": []string{"value-modified1"}}},
},
},
},
@@ -2446,7 +2422,7 @@ func TestAppStatusIsReplaced(t *testing.T) {
require.NoError(t, err)
require.True(t, ok)
- patchObj := map[string]any{}
+ patchObj := map[string]interface{}{}
require.NoError(t, json.Unmarshal(patchData, &patchObj))
val, has, err := unstructured.NestedFieldNoCopy(patchObj, "sync", "comparedTo", "destination", "server")
@@ -2718,7 +2694,7 @@ func TestSyncTimeout(t *testing.T) {
}
ctrl.processRequestedAppOperation(app)
- app, err := ctrl.applicationClientset.ArgoprojV1alpha1().Applications(app.ObjectMeta.Namespace).Get(t.Context(), app.Name, metav1.GetOptions{})
+ app, err := ctrl.applicationClientset.ArgoprojV1alpha1().Applications(app.ObjectMeta.Namespace).Get(context.Background(), app.ObjectMeta.Name, metav1.GetOptions{})
require.NoError(t, err)
require.Equal(t, tc.expectedPhase, app.Status.OperationState.Phase)
require.Equal(t, tc.expectedMessage, app.Status.OperationState.Message)
diff --git a/controller/cache/cache.go b/controller/cache/cache.go
index 99f85d50bb..73a8d0bc60 100644
--- a/controller/cache/cache.go
+++ b/controller/cache/cache.go
@@ -20,8 +20,8 @@ import (
"github.com/argoproj/gitops-engine/pkg/utils/kube"
log "github.com/sirupsen/logrus"
"golang.org/x/sync/semaphore"
- corev1 "k8s.io/api/core/v1"
- apierrors "k8s.io/apimachinery/pkg/api/errors"
+ v1 "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"
"k8s.io/apimachinery/pkg/runtime/schema"
@@ -29,17 +29,17 @@ import (
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/cache"
- "github.com/argoproj/argo-cd/v3/controller/metrics"
- "github.com/argoproj/argo-cd/v3/controller/sharding"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application"
- appv1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- "github.com/argoproj/argo-cd/v3/util/argo"
- "github.com/argoproj/argo-cd/v3/util/argo/normalizers"
- "github.com/argoproj/argo-cd/v3/util/db"
- "github.com/argoproj/argo-cd/v3/util/env"
- logutils "github.com/argoproj/argo-cd/v3/util/log"
- "github.com/argoproj/argo-cd/v3/util/lua"
- "github.com/argoproj/argo-cd/v3/util/settings"
+ "github.com/argoproj/argo-cd/v2/controller/metrics"
+ "github.com/argoproj/argo-cd/v2/controller/sharding"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application"
+ appv1 "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/argo/normalizers"
+ "github.com/argoproj/argo-cd/v2/util/db"
+ "github.com/argoproj/argo-cd/v2/util/env"
+ logutils "github.com/argoproj/argo-cd/v2/util/log"
+ "github.com/argoproj/argo-cd/v2/util/lua"
+ "github.com/argoproj/argo-cd/v2/util/settings"
)
const (
@@ -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 = false
+ clusterCacheRetryUseBackoff bool = false
// clusterCacheBatchEventsProcessing specifies whether to enable batch events processing
- clusterCacheBatchEventsProcessing = false
+ clusterCacheBatchEventsProcessing bool = false
// clusterCacheEventsProcessingInterval specifies the interval between processing events when BatchEventsProcessing is enabled
clusterCacheEventsProcessingInterval = 100 * time.Millisecond
@@ -126,49 +126,47 @@ func init() {
clusterCacheListSemaphoreSize = env.ParseInt64FromEnv(EnvClusterCacheListSemaphore, clusterCacheListSemaphoreSize, 0, math.MaxInt64)
clusterCacheAttemptLimit = int32(env.ParseNumFromEnv(EnvClusterCacheAttemptLimit, int(clusterCacheAttemptLimit), 1, math.MaxInt32))
clusterCacheRetryUseBackoff = env.ParseBoolFromEnv(EnvClusterCacheRetryUseBackoff, false)
- clusterCacheBatchEventsProcessing = env.ParseBoolFromEnv(EnvClusterCacheBatchEventsProcessing, true)
+ clusterCacheBatchEventsProcessing = env.ParseBoolFromEnv(EnvClusterCacheBatchEventsProcessing, false)
clusterCacheEventsProcessingInterval = env.ParseDurationFromEnv(EnvClusterCacheEventsProcessingInterval, clusterCacheEventsProcessingInterval, 0, math.MaxInt64)
}
type LiveStateCache interface {
// Returns k8s server version
- GetVersionsInfo(server *appv1.Cluster) (string, []kube.APIResourceInfo, error)
+ GetVersionsInfo(serverURL string) (string, []kube.APIResourceInfo, error)
// Returns true of given group kind is a namespaced resource
- IsNamespaced(server *appv1.Cluster, gk schema.GroupKind) (bool, error)
+ IsNamespaced(server string, gk schema.GroupKind) (bool, error)
// Returns synced cluster cache
- GetClusterCache(server *appv1.Cluster) (clustercache.ClusterCache, error)
+ GetClusterCache(server string) (clustercache.ClusterCache, error)
// Executes give callback against resource specified by the key and all its children
- IterateHierarchy(server *appv1.Cluster, key kube.ResourceKey, action func(child appv1.ResourceNode, appName string) bool) error
+ IterateHierarchy(server string, key kube.ResourceKey, action func(child appv1.ResourceNode, appName string) bool) error
// Executes give callback against resources specified by the keys and all its children
- IterateHierarchyV2(server *appv1.Cluster, keys []kube.ResourceKey, action func(child appv1.ResourceNode, appName string) bool) error
+ IterateHierarchyV2(server string, keys []kube.ResourceKey, action func(child appv1.ResourceNode, appName string) bool) error
// Returns state of live nodes which correspond for target nodes of specified application.
- GetManagedLiveObjs(destCluster *appv1.Cluster, a *appv1.Application, targetObjs []*unstructured.Unstructured) (map[kube.ResourceKey]*unstructured.Unstructured, error)
+ GetManagedLiveObjs(a *appv1.Application, targetObjs []*unstructured.Unstructured) (map[kube.ResourceKey]*unstructured.Unstructured, error)
// IterateResources iterates all resource stored in cache
- IterateResources(server *appv1.Cluster, callback func(res *clustercache.Resource, info *ResourceInfo)) error
+ IterateResources(server string, callback func(res *clustercache.Resource, info *ResourceInfo)) error
// Returns all top level resources (resources without owner references) of a specified namespace
- GetNamespaceTopLevelResources(server *appv1.Cluster, namespace string) (map[kube.ResourceKey]appv1.ResourceNode, error)
+ GetNamespaceTopLevelResources(server string, namespace string) (map[kube.ResourceKey]appv1.ResourceNode, error)
// Starts watching resources of each controlled cluster.
Run(ctx context.Context) error
// Returns information about monitored clusters
GetClustersInfo() []clustercache.ClusterInfo
// Init must be executed before cache can be used
Init() error
- // UpdateShard will update the shard of ClusterSharding when the shard has changed.
- UpdateShard(shard int) bool
}
-type ObjectUpdatedHandler = func(managedByApp map[string]bool, ref corev1.ObjectReference)
+type ObjectUpdatedHandler = func(managedByApp map[string]bool, ref v1.ObjectReference)
type PodInfo struct {
NodeName string
- ResourceRequests corev1.ResourceList
- Phase corev1.PodPhase
+ ResourceRequests v1.ResourceList
+ Phase v1.PodPhase
}
type NodeInfo struct {
Name string
- Capacity corev1.ResourceList
- SystemInfo corev1.NodeSystemInfo
+ Capacity v1.ResourceList
+ SystemInfo v1.NodeSystemInfo
}
type ResourceInfo struct {
@@ -242,10 +240,6 @@ func (c *liveStateCache) loadCacheSettings() (*cacheSettings, error) {
if err != nil {
return nil, err
}
- trackingMethod, err := c.settingsMgr.GetTrackingMethod()
- if err != nil {
- return nil, err
- }
installationID, err := c.settingsMgr.GetInstallationID()
if err != nil {
return nil, err
@@ -271,7 +265,7 @@ func (c *liveStateCache) loadCacheSettings() (*cacheSettings, error) {
ResourcesFilter: resourcesFilter,
}
- return &cacheSettings{clusterSettings, appInstanceLabelKey, appv1.TrackingMethod(trackingMethod), installationID, resourceUpdatesOverrides, ignoreResourceUpdatesEnabled}, nil
+ return &cacheSettings{clusterSettings, appInstanceLabelKey, argo.GetTrackingMethod(c.settingsMgr), installationID, resourceUpdatesOverrides, ignoreResourceUpdatesEnabled}, nil
}
func asResourceNode(r *clustercache.Resource) appv1.ResourceNode {
@@ -282,14 +276,8 @@ func asResourceNode(r *clustercache.Resource) appv1.ResourceNode {
parentRefs := make([]appv1.ResourceRef, len(r.OwnerRefs))
for i, ownerRef := range r.OwnerRefs {
ownerGvk := schema.FromAPIVersionAndKind(ownerRef.APIVersion, ownerRef.Kind)
- parentRefs[i] = appv1.ResourceRef{
- Group: ownerGvk.Group,
- Kind: ownerGvk.Kind,
- Version: ownerGvk.Version,
- Namespace: r.Ref.Namespace,
- Name: ownerRef.Name,
- UID: string(ownerRef.UID),
- }
+ ownerKey := kube.NewResourceKey(ownerGvk.Group, ownerRef.Kind, r.Ref.Namespace, ownerRef.Name)
+ parentRefs[i] = appv1.ResourceRef{Name: ownerRef.Name, Kind: ownerKey.Kind, Namespace: r.Ref.Namespace, Group: ownerKey.Group, UID: string(ownerRef.UID)}
}
var resHealth *appv1.HealthStatus
resourceInfo := resInfo(r)
@@ -341,11 +329,12 @@ func ownerRefGV(ownerRef metav1.OwnerReference) schema.GroupVersion {
}
func getAppRecursive(r *clustercache.Resource, ns map[kube.ResourceKey]*clustercache.Resource, visited map[kube.ResourceKey]bool) (string, bool) {
- if visited[r.ResourceKey()] {
+ if !visited[r.ResourceKey()] {
+ visited[r.ResourceKey()] = true
+ } else {
log.Warnf("Circular dependency detected: %v.", visited)
return resInfo(r).AppName, false
}
- visited[r.ResourceKey()] = true
if resInfo(r).AppName != "" {
return resInfo(r).AppName, true
@@ -353,11 +342,11 @@ func getAppRecursive(r *clustercache.Resource, ns map[kube.ResourceKey]*clusterc
for _, ownerRef := range r.OwnerRefs {
gv := ownerRefGV(ownerRef)
if parent, ok := ns[kube.NewResourceKey(gv.Group, ownerRef.Kind, r.Ref.Namespace, ownerRef.Name)]; ok {
- visitedBranch := make(map[kube.ResourceKey]bool, len(visited))
+ visited_branch := make(map[kube.ResourceKey]bool, len(visited))
for k, v := range visited {
- visitedBranch[k] = v
+ visited_branch[k] = v
}
- app, ok := getAppRecursive(parent, ns, visitedBranch)
+ app, ok := getAppRecursive(parent, ns, visited_branch)
if app != "" || !ok {
return app, ok
}
@@ -420,14 +409,14 @@ func isRetryableError(err error) bool {
if err == nil {
return false
}
- 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) ||
+ 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) ||
isResourceQuotaConflictErr(err) ||
isTransientNetworkErr(err) ||
isExceededQuotaErr(err) ||
@@ -440,16 +429,17 @@ func isHTTP2GoawayErr(err error) bool {
}
func isExceededQuotaErr(err error) bool {
- return apierrors.IsForbidden(err) && strings.Contains(err.Error(), "exceeded quota")
+ return kerrors.IsForbidden(err) && strings.Contains(err.Error(), "exceeded quota")
}
func isResourceQuotaConflictErr(err error) bool {
- return apierrors.IsConflict(err) && strings.Contains(err.Error(), "Operation cannot be fulfilled on resourcequota")
+ return kerrors.IsConflict(err) && strings.Contains(err.Error(), "Operation cannot be fulfilled on resourcequota")
}
func isTransientNetworkErr(err error) bool {
var netErr net.Error
- if errors.As(err, &netErr) {
+ switch {
+ case errors.As(err, &netErr):
var dnsErr *net.DNSError
var opErr *net.OpError
var unknownNetworkErr net.UnknownNetworkError
@@ -478,9 +468,9 @@ func isTransientNetworkErr(err error) bool {
return false
}
-func (c *liveStateCache) getCluster(cluster *appv1.Cluster) (clustercache.ClusterCache, error) {
+func (c *liveStateCache) getCluster(server string) (clustercache.ClusterCache, error) {
c.lock.RLock()
- clusterCache, ok := c.clusters[cluster.Server]
+ clusterCache, ok := c.clusters[server]
cacheSettings := c.cacheSettings
c.lock.RUnlock()
@@ -491,11 +481,16 @@ func (c *liveStateCache) getCluster(cluster *appv1.Cluster) (clustercache.Cluste
c.lock.Lock()
defer c.lock.Unlock()
- clusterCache, ok = c.clusters[cluster.Server]
+ clusterCache, ok = c.clusters[server]
if ok {
return clusterCache, nil
}
+ cluster, err := c.db.GetCluster(context.Background(), server)
+ if err != nil {
+ return nil, fmt.Errorf("error getting cluster: %w", err)
+ }
+
if c.clusterSharding == nil {
return nil, fmt.Errorf("unable to handle cluster %s: cluster sharding is not configured", cluster.Server)
}
@@ -541,7 +536,7 @@ func (c *liveStateCache) getCluster(cluster *appv1.Cluster) (clustercache.Cluste
clustercache.SetSettings(cacheSettings.clusterSettings),
clustercache.SetNamespaces(cluster.Namespaces),
clustercache.SetClusterResources(cluster.ClusterResources),
- clustercache.SetPopulateResourceInfoHandler(func(un *unstructured.Unstructured, isRoot bool) (any, bool) {
+ clustercache.SetPopulateResourceInfoHandler(func(un *unstructured.Unstructured, isRoot bool) (interface{}, bool) {
res := &ResourceInfo{}
populateNodeInfo(un, res, resourceCustomLabels)
c.lock.RLock()
@@ -581,7 +576,7 @@ func (c *liveStateCache) getCluster(cluster *appv1.Cluster) (clustercache.Cluste
_ = clusterCache.OnResourceUpdated(func(newRes *clustercache.Resource, oldRes *clustercache.Resource, namespaceResources map[kube.ResourceKey]*clustercache.Resource) {
toNotify := make(map[string]bool)
- var ref corev1.ObjectReference
+ var ref v1.ObjectReference
if newRes != nil {
ref = newRes.Ref
} else {
@@ -624,7 +619,7 @@ func (c *liveStateCache) getCluster(cluster *appv1.Cluster) (clustercache.Cluste
c.onObjectUpdated(toNotify, ref)
})
- _ = clusterCache.OnEvent(func(_ watch.EventType, un *unstructured.Unstructured) {
+ _ = clusterCache.OnEvent(func(event watch.EventType, un *unstructured.Unstructured) {
gvk := un.GroupVersionKind()
c.metricsServer.IncClusterEventsCount(cluster.Server, gvk.Group, gvk.Kind)
})
@@ -633,12 +628,12 @@ func (c *liveStateCache) getCluster(cluster *appv1.Cluster) (clustercache.Cluste
c.metricsServer.ObserveResourceEventsProcessingDuration(cluster.Server, duration, processedEventsNumber)
})
- c.clusters[cluster.Server] = clusterCache
+ c.clusters[server] = clusterCache
return clusterCache, nil
}
-func (c *liveStateCache) getSyncedCluster(server *appv1.Cluster) (clustercache.ClusterCache, error) {
+func (c *liveStateCache) getSyncedCluster(server string) (clustercache.ClusterCache, error) {
clusterCache, err := c.getCluster(server)
if err != nil {
return nil, fmt.Errorf("error getting cluster: %w", err)
@@ -663,7 +658,7 @@ func (c *liveStateCache) invalidate(cacheSettings cacheSettings) {
log.Info("live state cache invalidated")
}
-func (c *liveStateCache) IsNamespaced(server *appv1.Cluster, gk schema.GroupKind) (bool, error) {
+func (c *liveStateCache) IsNamespaced(server string, gk schema.GroupKind) (bool, error) {
clusterInfo, err := c.getSyncedCluster(server)
if err != nil {
return false, err
@@ -671,7 +666,7 @@ func (c *liveStateCache) IsNamespaced(server *appv1.Cluster, gk schema.GroupKind
return clusterInfo.IsNamespaced(gk)
}
-func (c *liveStateCache) IterateHierarchy(server *appv1.Cluster, key kube.ResourceKey, action func(child appv1.ResourceNode, appName string) bool) error {
+func (c *liveStateCache) IterateHierarchy(server string, key kube.ResourceKey, action func(child appv1.ResourceNode, appName string) bool) error {
clusterInfo, err := c.getSyncedCluster(server)
if err != nil {
return err
@@ -682,7 +677,7 @@ func (c *liveStateCache) IterateHierarchy(server *appv1.Cluster, key kube.Resour
return nil
}
-func (c *liveStateCache) IterateHierarchyV2(server *appv1.Cluster, keys []kube.ResourceKey, action func(child appv1.ResourceNode, appName string) bool) error {
+func (c *liveStateCache) IterateHierarchyV2(server string, keys []kube.ResourceKey, action func(child appv1.ResourceNode, appName string) bool) error {
clusterInfo, err := c.getSyncedCluster(server)
if err != nil {
return err
@@ -693,7 +688,7 @@ func (c *liveStateCache) IterateHierarchyV2(server *appv1.Cluster, keys []kube.R
return nil
}
-func (c *liveStateCache) IterateResources(server *appv1.Cluster, callback func(res *clustercache.Resource, info *ResourceInfo)) error {
+func (c *liveStateCache) IterateResources(server string, callback func(res *clustercache.Resource, info *ResourceInfo)) error {
clusterInfo, err := c.getSyncedCluster(server)
if err != nil {
return err
@@ -707,7 +702,7 @@ func (c *liveStateCache) IterateResources(server *appv1.Cluster, callback func(r
return nil
}
-func (c *liveStateCache) GetNamespaceTopLevelResources(server *appv1.Cluster, namespace string) (map[kube.ResourceKey]appv1.ResourceNode, error) {
+func (c *liveStateCache) GetNamespaceTopLevelResources(server string, namespace string) (map[kube.ResourceKey]appv1.ResourceNode, error) {
clusterInfo, err := c.getSyncedCluster(server)
if err != nil {
return nil, err
@@ -720,36 +715,35 @@ func (c *liveStateCache) GetNamespaceTopLevelResources(server *appv1.Cluster, na
return res, nil
}
-func (c *liveStateCache) GetManagedLiveObjs(destCluster *appv1.Cluster, a *appv1.Application, targetObjs []*unstructured.Unstructured) (map[kube.ResourceKey]*unstructured.Unstructured, error) {
- clusterInfo, err := c.getSyncedCluster(destCluster)
+func (c *liveStateCache) GetManagedLiveObjs(a *appv1.Application, targetObjs []*unstructured.Unstructured) (map[kube.ResourceKey]*unstructured.Unstructured, error) {
+ clusterInfo, err := c.getSyncedCluster(a.Spec.Destination.Server)
if err != nil {
- return nil, fmt.Errorf("failed to get cluster info for %q: %w", destCluster.Server, err)
+ return nil, fmt.Errorf("failed to get cluster info for %q: %w", a.Spec.Destination.Server, err)
}
return clusterInfo.GetManagedLiveObjs(targetObjs, func(r *clustercache.Resource) bool {
return resInfo(r).AppName == a.InstanceName(c.settingsMgr.GetNamespace())
})
}
-func (c *liveStateCache) GetVersionsInfo(server *appv1.Cluster) (string, []kube.APIResourceInfo, error) {
- clusterInfo, err := c.getSyncedCluster(server)
+func (c *liveStateCache) GetVersionsInfo(serverURL string) (string, []kube.APIResourceInfo, error) {
+ clusterInfo, err := c.getSyncedCluster(serverURL)
if err != nil {
- return "", nil, fmt.Errorf("failed to get cluster info for %q: %w", server.Server, err)
+ return "", nil, fmt.Errorf("failed to get cluster info for %q: %w", serverURL, err)
}
return clusterInfo.GetServerVersion(), clusterInfo.GetAPIResources(), nil
}
-func (c *liveStateCache) isClusterHasApps(apps []any, cluster *appv1.Cluster) bool {
+func (c *liveStateCache) isClusterHasApps(apps []interface{}, cluster *appv1.Cluster) bool {
for _, obj := range apps {
app, ok := obj.(*appv1.Application)
if !ok {
continue
}
- destCluster, err := argo.GetDestinationCluster(context.Background(), app.Spec.Destination, c.db)
+ err := argo.ValidateDestination(context.Background(), &app.Spec.Destination, c.db)
if err != nil {
- log.Warnf("Failed to get destination cluster: %v", err)
continue
}
- if destCluster.Server == cluster.Server {
+ if app.Spec.Destination.Server == cluster.Server {
return true
}
}
@@ -833,7 +827,7 @@ func (c *liveStateCache) handleAddEvent(cluster *appv1.Cluster) {
if c.isClusterHasApps(c.appInformer.GetStore().List(), cluster) {
go func() {
// warm up cache for cluster with apps
- _, _ = c.getSyncedCluster(cluster)
+ _, _ = c.getSyncedCluster(cluster.Server)
}()
}
}
@@ -915,11 +909,6 @@ func (c *liveStateCache) GetClustersInfo() []clustercache.ClusterInfo {
return res
}
-func (c *liveStateCache) GetClusterCache(server *appv1.Cluster) (clustercache.ClusterCache, error) {
+func (c *liveStateCache) GetClusterCache(server string) (clustercache.ClusterCache, error) {
return c.getSyncedCluster(server)
}
-
-// UpdateShard will update the shard of ClusterSharding when the shard has changed.
-func (c *liveStateCache) UpdateShard(shard int) bool {
- return c.clusterSharding.UpdateShard(shard)
-}
diff --git a/controller/cache/cache_test.go b/controller/cache/cache_test.go
index 006f5108da..652b4b5549 100644
--- a/controller/cache/cache_test.go
+++ b/controller/cache/cache_test.go
@@ -1,6 +1,7 @@
package cache
import (
+ "context"
"errors"
"net"
"net/url"
@@ -8,12 +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"
- apierrors "k8s.io/apimachinery/pkg/api/errors"
+ 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"
@@ -24,13 +24,13 @@ import (
"github.com/stretchr/testify/mock"
"k8s.io/client-go/kubernetes/fake"
- "github.com/argoproj/argo-cd/v3/common"
- "github.com/argoproj/argo-cd/v3/controller/metrics"
- "github.com/argoproj/argo-cd/v3/controller/sharding"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application"
- appv1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- dbmocks "github.com/argoproj/argo-cd/v3/util/db/mocks"
- argosettings "github.com/argoproj/argo-cd/v3/util/settings"
+ "github.com/argoproj/argo-cd/v2/common"
+ "github.com/argoproj/argo-cd/v2/controller/metrics"
+ "github.com/argoproj/argo-cd/v2/controller/sharding"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application"
+ appv1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+ dbmocks "github.com/argoproj/argo-cd/v2/util/db/mocks"
+ argosettings "github.com/argoproj/argo-cd/v2/util/settings"
)
type netError string
@@ -39,7 +39,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(_ *testing.T) {
+func TestHandleModEvent_HasChanges(t *testing.T) {
clusterCache := &mocks.ClusterCache{}
clusterCache.On("Invalidate", mock.Anything, mock.Anything).Return(nil).Once()
clusterCache.On("EnsureSynced").Return(nil).Once()
@@ -71,7 +71,7 @@ func TestHandleModEvent_ClusterExcluded(t *testing.T) {
clustersCache := liveStateCache{
db: nil,
appInformer: nil,
- onObjectUpdated: func(_ map[string]bool, _ corev1.ObjectReference) {
+ onObjectUpdated: func(managedByApp map[string]bool, ref v1.ObjectReference) {
},
kubectl: nil,
settingsMgr: &argosettings.SettingsManager{},
@@ -96,7 +96,7 @@ func TestHandleModEvent_ClusterExcluded(t *testing.T) {
assert.Len(t, clustersCache.clusters, 1)
}
-func TestHandleModEvent_NoChanges(_ *testing.T) {
+func TestHandleModEvent_NoChanges(t *testing.T) {
clusterCache := &mocks.ClusterCache{}
clusterCache.On("Invalidate", mock.Anything).Panic("should not invalidate")
clusterCache.On("EnsureSynced").Return(nil).Panic("should not re-sync")
@@ -141,7 +141,7 @@ func TestHandleDeleteEvent_CacheDeadlock(t *testing.T) {
db := &dbmocks.ArgoDB{}
db.On("GetApplicationControllerReplicas").Return(1)
fakeClient := fake.NewClientset()
- settingsMgr := argosettings.NewSettingsManager(t.Context(), fakeClient, "argocd")
+ settingsMgr := argosettings.NewSettingsManager(context.TODO(), fakeClient, "argocd")
liveStateCacheLock := sync.RWMutex{}
gitopsEngineClusterCache := &mocks.ClusterCache{}
clustersCache := liveStateCache{
@@ -151,7 +151,7 @@ func TestHandleDeleteEvent_CacheDeadlock(t *testing.T) {
clusterSharding: sharding.NewClusterSharding(db, 0, 1, common.DefaultShardingAlgorithm),
settingsMgr: settingsMgr,
// Set the lock here so we can reference it later
- //nolint:govet // We need to overwrite here to have access to the lock
+ // nolint We need to overwrite here to have access to the lock
lock: liveStateCacheLock,
}
channel := make(chan string)
@@ -173,7 +173,7 @@ func TestHandleDeleteEvent_CacheDeadlock(t *testing.T) {
handleDeleteWasCalled.Lock()
engineHoldsEngineLock.Lock()
- gitopsEngineClusterCache.On("EnsureSynced").Run(func(_ mock.Arguments) {
+ gitopsEngineClusterCache.On("EnsureSynced").Run(func(args mock.Arguments) {
gitopsEngineClusterCacheLock.Lock()
t.Log("EnsureSynced: Engine has engine lock")
engineHoldsEngineLock.Unlock()
@@ -187,7 +187,7 @@ func TestHandleDeleteEvent_CacheDeadlock(t *testing.T) {
ensureSyncedCompleted.Unlock()
}).Return(nil).Once()
- gitopsEngineClusterCache.On("Invalidate").Run(func(_ mock.Arguments) {
+ gitopsEngineClusterCache.On("Invalidate").Run(func(args mock.Arguments) {
// Allow EnsureSynced to continue now that we're in the deadlock condition
handleDeleteWasCalled.Unlock()
// Wait until gitops engine holds the gitops lock
@@ -238,15 +238,15 @@ func TestIsRetryableError(t *testing.T) {
assert.False(t, isRetryableError(nil))
})
t.Run("ResourceQuotaConflictErr", func(t *testing.T) {
- assert.False(t, isRetryableError(apierrors.NewConflict(schema.GroupResource{}, "", nil)))
- assert.True(t, isRetryableError(apierrors.NewConflict(schema.GroupResource{Group: "v1", Resource: "resourcequotas"}, "", nil)))
+ assert.False(t, isRetryableError(apierr.NewConflict(schema.GroupResource{}, "", nil)))
+ assert.True(t, isRetryableError(apierr.NewConflict(schema.GroupResource{Group: "v1", Resource: "resourcequotas"}, "", nil)))
})
t.Run("ExceededQuotaErr", func(t *testing.T) {
- 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"))))
+ 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"))))
})
t.Run("TooManyRequestsDNS", func(t *testing.T) {
- assert.True(t, isRetryableError(apierrors.NewTooManyRequests("", 0)))
+ assert.True(t, isRetryableError(apierr.NewTooManyRequests("", 0)))
})
t.Run("DNSError", func(t *testing.T) {
assert.True(t, isRetryableError(&net.DNSError{}))
@@ -278,7 +278,7 @@ func TestIsRetryableError(t *testing.T) {
func Test_asResourceNode_owner_refs(t *testing.T) {
resNode := asResourceNode(&cache.Resource{
ResourceVersion: "",
- Ref: corev1.ObjectReference{
+ Ref: v1.ObjectReference{
APIVersion: "v1",
},
OwnerRefs: []metav1.OwnerReference{
@@ -303,16 +303,14 @@ func Test_asResourceNode_owner_refs(t *testing.T) {
},
ParentRefs: []appv1.ResourceRef{
{
- Group: "",
- Kind: "ConfigMap",
- Version: "v1",
- Name: "cm-1",
+ Group: "",
+ Kind: "ConfigMap",
+ Name: "cm-1",
},
{
- Group: "",
- Kind: "ConfigMap",
- Version: "v1",
- Name: "cm-2",
+ Group: "",
+ Kind: "ConfigMap",
+ Name: "cm-2",
},
},
Info: nil,
@@ -336,7 +334,7 @@ func Test_getAppRecursive(t *testing.T) {
{
name: "ok: cm1->app1",
r: &cache.Resource{
- Ref: corev1.ObjectReference{
+ Ref: v1.ObjectReference{
Name: "cm1",
},
OwnerRefs: []metav1.OwnerReference{
@@ -356,7 +354,7 @@ func Test_getAppRecursive(t *testing.T) {
{
name: "ok: cm1->cm2->app1",
r: &cache.Resource{
- Ref: corev1.ObjectReference{
+ Ref: v1.ObjectReference{
Name: "cm1",
},
OwnerRefs: []metav1.OwnerReference{
@@ -365,7 +363,7 @@ func Test_getAppRecursive(t *testing.T) {
},
ns: map[kube.ResourceKey]*cache.Resource{
kube.NewResourceKey("", "", "", "cm2"): {
- Ref: corev1.ObjectReference{
+ Ref: v1.ObjectReference{
Name: "cm2",
},
OwnerRefs: []metav1.OwnerReference{
@@ -384,7 +382,7 @@ func Test_getAppRecursive(t *testing.T) {
{
name: "cm1->cm2->app1 & cm1->cm3->app1",
r: &cache.Resource{
- Ref: corev1.ObjectReference{
+ Ref: v1.ObjectReference{
Name: "cm1",
},
OwnerRefs: []metav1.OwnerReference{
@@ -394,7 +392,7 @@ func Test_getAppRecursive(t *testing.T) {
},
ns: map[kube.ResourceKey]*cache.Resource{
kube.NewResourceKey("", "", "", "cm2"): {
- Ref: corev1.ObjectReference{
+ Ref: v1.ObjectReference{
Name: "cm2",
},
OwnerRefs: []metav1.OwnerReference{
@@ -402,7 +400,7 @@ func Test_getAppRecursive(t *testing.T) {
},
},
kube.NewResourceKey("", "", "", "cm3"): {
- Ref: corev1.ObjectReference{
+ Ref: v1.ObjectReference{
Name: "cm3",
},
OwnerRefs: []metav1.OwnerReference{
@@ -423,7 +421,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: corev1.ObjectReference{
+ Ref: v1.ObjectReference{
Name: "cm1",
},
OwnerRefs: []metav1.OwnerReference{
@@ -433,12 +431,12 @@ func Test_getAppRecursive(t *testing.T) {
},
ns: map[kube.ResourceKey]*cache.Resource{
kube.NewResourceKey("", "", "", "cm2"): {
- Ref: corev1.ObjectReference{
+ Ref: v1.ObjectReference{
Name: "cm2",
},
},
kube.NewResourceKey("", "", "", "cm3"): {
- Ref: corev1.ObjectReference{
+ Ref: v1.ObjectReference{
Name: "cm3",
},
OwnerRefs: []metav1.OwnerReference{
@@ -458,7 +456,7 @@ func Test_getAppRecursive(t *testing.T) {
{
name: "cycle: cm1<->cm2",
r: &cache.Resource{
- Ref: corev1.ObjectReference{
+ Ref: v1.ObjectReference{
Name: "cm1",
},
OwnerRefs: []metav1.OwnerReference{
@@ -467,7 +465,7 @@ func Test_getAppRecursive(t *testing.T) {
},
ns: map[kube.ResourceKey]*cache.Resource{
kube.NewResourceKey("", "", "", "cm1"): {
- Ref: corev1.ObjectReference{
+ Ref: v1.ObjectReference{
Name: "cm1",
},
OwnerRefs: []metav1.OwnerReference{
@@ -475,7 +473,7 @@ func Test_getAppRecursive(t *testing.T) {
},
},
kube.NewResourceKey("", "", "", "cm2"): {
- Ref: corev1.ObjectReference{
+ Ref: v1.ObjectReference{
Name: "cm2",
},
OwnerRefs: []metav1.OwnerReference{
@@ -489,7 +487,7 @@ func Test_getAppRecursive(t *testing.T) {
{
name: "cycle: cm1->cm2->cm3->cm1",
r: &cache.Resource{
- Ref: corev1.ObjectReference{
+ Ref: v1.ObjectReference{
Name: "cm1",
},
OwnerRefs: []metav1.OwnerReference{
@@ -498,7 +496,7 @@ func Test_getAppRecursive(t *testing.T) {
},
ns: map[kube.ResourceKey]*cache.Resource{
kube.NewResourceKey("", "", "", "cm1"): {
- Ref: corev1.ObjectReference{
+ Ref: v1.ObjectReference{
Name: "cm1",
},
OwnerRefs: []metav1.OwnerReference{
@@ -506,7 +504,7 @@ func Test_getAppRecursive(t *testing.T) {
},
},
kube.NewResourceKey("", "", "", "cm2"): {
- Ref: corev1.ObjectReference{
+ Ref: v1.ObjectReference{
Name: "cm2",
},
OwnerRefs: []metav1.OwnerReference{
@@ -514,7 +512,7 @@ func Test_getAppRecursive(t *testing.T) {
},
},
kube.NewResourceKey("", "", "", "cm3"): {
- Ref: corev1.ObjectReference{
+ Ref: v1.ObjectReference{
Name: "cm3",
},
OwnerRefs: []metav1.OwnerReference{
@@ -537,12 +535,12 @@ func Test_getAppRecursive(t *testing.T) {
func TestSkipResourceUpdate(t *testing.T) {
var (
- hash1X = "x"
- hash2Y = "y"
- hash3X = "x"
+ hash1_x string = "x"
+ hash2_y string = "y"
+ hash3_x string = "x"
)
info := &ResourceInfo{
- manifestHash: hash1X,
+ manifestHash: hash1_x,
Health: &health.HealthStatus{
Status: health.HealthStatusHealthy,
Message: "default",
@@ -562,51 +560,51 @@ func TestSkipResourceUpdate(t *testing.T) {
})
t.Run("Same hash", func(t *testing.T) {
assert.True(t, skipResourceUpdate(&ResourceInfo{
- manifestHash: hash1X,
+ manifestHash: hash1_x,
}, &ResourceInfo{
- manifestHash: hash1X,
+ manifestHash: hash1_x,
}))
})
t.Run("Same hash value", func(t *testing.T) {
assert.True(t, skipResourceUpdate(&ResourceInfo{
- manifestHash: hash1X,
+ manifestHash: hash1_x,
}, &ResourceInfo{
- manifestHash: hash3X,
+ manifestHash: hash3_x,
}))
})
t.Run("Different hash value", func(t *testing.T) {
assert.False(t, skipResourceUpdate(&ResourceInfo{
- manifestHash: hash1X,
+ manifestHash: hash1_x,
}, &ResourceInfo{
- manifestHash: hash2Y,
+ manifestHash: hash2_y,
}))
})
t.Run("Same hash, empty health", func(t *testing.T) {
assert.True(t, skipResourceUpdate(&ResourceInfo{
- manifestHash: hash1X,
+ manifestHash: hash1_x,
Health: &health.HealthStatus{},
}, &ResourceInfo{
- manifestHash: hash3X,
+ manifestHash: hash3_x,
Health: &health.HealthStatus{},
}))
})
t.Run("Same hash, old health", func(t *testing.T) {
assert.False(t, skipResourceUpdate(&ResourceInfo{
- manifestHash: hash1X,
+ manifestHash: hash1_x,
Health: &health.HealthStatus{
Status: health.HealthStatusHealthy,
},
}, &ResourceInfo{
- manifestHash: hash3X,
+ manifestHash: hash3_x,
Health: nil,
}))
})
t.Run("Same hash, new health", func(t *testing.T) {
assert.False(t, skipResourceUpdate(&ResourceInfo{
- manifestHash: hash1X,
+ manifestHash: hash1_x,
Health: &health.HealthStatus{},
}, &ResourceInfo{
- manifestHash: hash3X,
+ manifestHash: hash3_x,
Health: &health.HealthStatus{
Status: health.HealthStatusHealthy,
},
@@ -614,13 +612,13 @@ func TestSkipResourceUpdate(t *testing.T) {
})
t.Run("Same hash, same health", func(t *testing.T) {
assert.True(t, skipResourceUpdate(&ResourceInfo{
- manifestHash: hash1X,
+ manifestHash: hash1_x,
Health: &health.HealthStatus{
Status: health.HealthStatusHealthy,
Message: "same",
},
}, &ResourceInfo{
- manifestHash: hash3X,
+ manifestHash: hash3_x,
Health: &health.HealthStatus{
Status: health.HealthStatusHealthy,
Message: "same",
@@ -629,13 +627,13 @@ func TestSkipResourceUpdate(t *testing.T) {
})
t.Run("Same hash, different health status", func(t *testing.T) {
assert.False(t, skipResourceUpdate(&ResourceInfo{
- manifestHash: hash1X,
+ manifestHash: hash1_x,
Health: &health.HealthStatus{
Status: health.HealthStatusHealthy,
Message: "same",
},
}, &ResourceInfo{
- manifestHash: hash3X,
+ manifestHash: hash3_x,
Health: &health.HealthStatus{
Status: health.HealthStatusDegraded,
Message: "same",
@@ -644,13 +642,13 @@ func TestSkipResourceUpdate(t *testing.T) {
})
t.Run("Same hash, different health message", func(t *testing.T) {
assert.True(t, skipResourceUpdate(&ResourceInfo{
- manifestHash: hash1X,
+ manifestHash: hash1_x,
Health: &health.HealthStatus{
Status: health.HealthStatusHealthy,
Message: "same",
},
}, &ResourceInfo{
- manifestHash: hash3X,
+ manifestHash: hash3_x,
Health: &health.HealthStatus{
Status: health.HealthStatusHealthy,
Message: "different",
@@ -728,21 +726,9 @@ func TestShouldHashManifest(t *testing.T) {
test.un.SetAnnotations(test.annotations)
}
got := shouldHashManifest(test.appName, test.gvk, test.un)
- require.Equalf(t, test.want, got, "test=%v", test.name)
+ if test.want != got {
+ t.Fatalf("test=%v want %v got %v", test.name, test.want, got)
+ }
})
}
}
-
-func Test_GetVersionsInfo_error_redacted(t *testing.T) {
- c := liveStateCache{}
- cluster := &appv1.Cluster{
- Server: "https://localhost:1234",
- Config: appv1.ClusterConfig{
- Username: "admin",
- Password: "password",
- },
- }
- _, _, err := c.GetVersionsInfo(cluster)
- require.Error(t, err)
- assert.NotContains(t, err.Error(), "password")
-}
diff --git a/controller/cache/info.go b/controller/cache/info.go
index 78de447bbe..635000e688 100644
--- a/controller/cache/info.go
+++ b/controller/cache/info.go
@@ -6,20 +6,20 @@ 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"
- "github.com/argoproj/argo-cd/v3/common"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- "github.com/argoproj/argo-cd/v3/util/argo/normalizers"
- "github.com/argoproj/argo-cd/v3/util/resource"
+ "github.com/argoproj/argo-cd/v2/common"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/util/argo/normalizers"
+ "github.com/argoproj/argo-cd/v2/util/resource"
)
func populateNodeInfo(un *unstructured.Unstructured, res *ResourceInfo, customLabels []string) {
@@ -58,7 +58,8 @@ func populateNodeInfo(un *unstructured.Unstructured, res *ResourceInfo, customLa
populateHostNodeInfo(un, res)
}
case "extensions", "networking.k8s.io":
- if gvk.Kind == kube.IngressKind {
+ switch gvk.Kind {
+ case kube.IngressKind:
populateIngressInfo(un, res)
}
case "networking.istio.io":
@@ -71,18 +72,18 @@ func populateNodeInfo(un *unstructured.Unstructured, res *ResourceInfo, customLa
}
}
-func getIngress(un *unstructured.Unstructured) []corev1.LoadBalancerIngress {
+func getIngress(un *unstructured.Unstructured) []v1.LoadBalancerIngress {
ingress, ok, err := unstructured.NestedSlice(un.Object, "status", "loadBalancer", "ingress")
if !ok || err != nil {
return nil
}
- res := make([]corev1.LoadBalancerIngress, 0)
+ res := make([]v1.LoadBalancerIngress, 0)
for _, item := range ingress {
- if lbIngress, ok := item.(map[string]any); ok {
+ if lbIngress, ok := item.(map[string]interface{}); ok {
if hostname := lbIngress["hostname"]; hostname != nil {
- res = append(res, corev1.LoadBalancerIngress{Hostname: fmt.Sprintf("%s", hostname)})
+ res = append(res, v1.LoadBalancerIngress{Hostname: fmt.Sprintf("%s", hostname)})
} else if ip := lbIngress["ip"]; ip != nil {
- res = append(res, corev1.LoadBalancerIngress{IP: fmt.Sprintf("%s", ip)})
+ res = append(res, v1.LoadBalancerIngress{IP: fmt.Sprintf("%s", ip)})
}
}
}
@@ -91,8 +92,8 @@ func getIngress(un *unstructured.Unstructured) []corev1.LoadBalancerIngress {
func populateServiceInfo(un *unstructured.Unstructured, res *ResourceInfo) {
targetLabels, _, _ := unstructured.NestedStringMap(un.Object, "spec", "selector")
- ingress := make([]corev1.LoadBalancerIngress, 0)
- if serviceType, ok, err := unstructured.NestedString(un.Object, "spec", "type"); ok && err == nil && serviceType == string(corev1.ServiceTypeLoadBalancer) {
+ ingress := make([]v1.LoadBalancerIngress, 0)
+ if serviceType, ok, err := unstructured.NestedString(un.Object, "spec", "type"); ok && err == nil && serviceType == string(v1.ServiceTypeLoadBalancer) {
ingress = getIngress(un)
}
@@ -104,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]any, gvk schema.GroupVersionKind) (string, error) {
+func getServiceName(backend map[string]interface{}, gvk schema.GroupVersionKind) (string, error) {
switch gvk.Group {
case "extensions":
return fmt.Sprintf("%s", backend["serviceName"]), nil
@@ -138,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]any)
+ rule, ok := rules[i].(map[string]interface{})
if !ok {
continue
}
@@ -156,7 +157,7 @@ func populateIngressInfo(un *unstructured.Unstructured, res *ResourceInfo) {
continue
}
for i := range paths {
- path, ok := paths[i].(map[string]any)
+ path, ok := paths[i].(map[string]interface{})
if !ok {
continue
}
@@ -178,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]any)
+ tlsline, ok := tls[i].(map[string]interface{})
secretName := tlsline["secretName"]
if ok && secretName != nil {
stringPort = "https"
@@ -189,7 +190,7 @@ func populateIngressInfo(un *unstructured.Unstructured, res *ResourceInfo) {
continue
}
if hosts := tlsline["hosts"]; hosts != nil {
- tlshosts, ok := tlsline["hosts"].(map[string]any)
+ tlshosts, ok := tlsline["hosts"].(map[string]interface{})
if ok {
for j := range tlshosts {
if tlshosts[j] == host {
@@ -232,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]any)
+ rule, ok := rules[i].(map[string]interface{})
if !ok {
continue
}
@@ -241,7 +242,7 @@ func populateIstioVirtualServiceInfo(un *unstructured.Unstructured, res *Resourc
continue
}
for i := range routes {
- route, ok := routes[i].(map[string]any)
+ route, ok := routes[i].(map[string]interface{})
if !ok {
continue
}
@@ -295,18 +296,18 @@ func populateIstioServiceEntryInfo(un *unstructured.Unstructured, res *ResourceI
}
}
-func isPodInitializedConditionTrue(status *corev1.PodStatus) bool {
+func isPodInitializedConditionTrue(status *v1.PodStatus) bool {
for _, condition := range status.Conditions {
- if condition.Type != corev1.PodInitialized {
+ if condition.Type != v1.PodInitialized {
continue
}
- return condition.Status == corev1.ConditionTrue
+ return condition.Status == v1.ConditionTrue
}
return false
}
-func isRestartableInitContainer(initContainer *corev1.Container) bool {
+func isRestartableInitContainer(initContainer *v1.Container) bool {
if initContainer == nil {
return false
}
@@ -314,15 +315,15 @@ func isRestartableInitContainer(initContainer *corev1.Container) bool {
return false
}
- return *initContainer.RestartPolicy == corev1.ContainerRestartPolicyAlways
+ return *initContainer.RestartPolicy == v1.ContainerRestartPolicyAlways
}
-func isPodPhaseTerminal(phase corev1.PodPhase) bool {
- return phase == corev1.PodFailed || phase == corev1.PodSucceeded
+func isPodPhaseTerminal(phase v1.PodPhase) bool {
+ return phase == v1.PodFailed || phase == v1.PodSucceeded
}
func populatePodInfo(un *unstructured.Unstructured, res *ResourceInfo) {
- pod := corev1.Pod{}
+ pod := v1.Pod{}
err := runtime.DefaultUnstructuredConverter.FromUnstructured(un.Object, &pod)
if err != nil {
return
@@ -352,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 == corev1.PodScheduled && condition.Reason == corev1.PodReasonSchedulingGated {
- reason = corev1.PodReasonSchedulingGated
+ if condition.Type == v1.PodScheduled && condition.Reason == v1.PodReasonSchedulingGated {
+ reason = v1.PodReasonSchedulingGated
}
}
- initContainers := make(map[string]*corev1.Container)
+ initContainers := make(map[string]*v1.Container)
for i := range pod.Spec.InitContainers {
initContainers[pod.Spec.InitContainers[i].Name] = &pod.Spec.InitContainers[i]
if isRestartableInitContainer(&pod.Spec.InitContainers[i]) {
@@ -405,18 +406,17 @@ func populatePodInfo(un *unstructured.Unstructured, res *ResourceInfo) {
container := pod.Status.ContainerStatuses[i]
restarts += int(container.RestartCount)
- switch {
- case container.State.Waiting != nil && container.State.Waiting.Reason != "":
+ if container.State.Waiting != nil && container.State.Waiting.Reason != "" {
reason = container.State.Waiting.Reason
- case container.State.Terminated != nil && container.State.Terminated.Reason != "":
+ } else if container.State.Terminated != nil && container.State.Terminated.Reason != "" {
reason = container.State.Terminated.Reason
- case container.State.Terminated != nil && container.State.Terminated.Reason == "":
+ } else if container.State.Terminated != nil && container.State.Terminated.Reason == "" {
if container.State.Terminated.Signal != 0 {
reason = fmt.Sprintf("Signal:%d", container.State.Terminated.Signal)
} else {
reason = fmt.Sprintf("ExitCode:%d", container.State.Terminated.ExitCode)
}
- case container.Ready && container.State.Running != nil:
+ } else if container.Ready && container.State.Running != nil {
hasRunning = true
readyContainers++
}
@@ -463,7 +463,7 @@ func populatePodInfo(un *unstructured.Unstructured, res *ResourceInfo) {
}
func populateHostNodeInfo(un *unstructured.Unstructured, res *ResourceInfo) {
- node := corev1.Node{}
+ node := v1.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 91f816fd15..db58d209f1 100644
--- a/controller/cache/info_test.go
+++ b/controller/cache/info_test.go
@@ -5,21 +5,22 @@ 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"
- corev1 "k8s.io/api/core/v1"
- "k8s.io/apimachinery/pkg/api/resource"
+ v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"sigs.k8s.io/yaml"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- "github.com/argoproj/argo-cd/v3/util/argo/normalizers"
- "github.com/argoproj/argo-cd/v3/util/errors"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/util/argo/normalizers"
)
func strToUnstructured(jsonStr string) *unstructured.Unstructured {
- obj := make(map[string]any)
+ obj := make(map[string]interface{})
err := yaml.Unmarshal([]byte(jsonStr), &obj)
errors.CheckError(err)
return &unstructured.Unstructured{Object: obj}
@@ -157,7 +158,7 @@ var (
ingress:
- ip: 107.178.210.11`)
- testIngressWithoutTLS = strToUnstructured(`
+ testIngressWithoutTls = strToUnstructured(`
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
@@ -309,7 +310,7 @@ func TestGetPodInfo(t *testing.T) {
assert.Equal(t, []string{"bar"}, info.Images)
assert.Equal(t, &PodInfo{
NodeName: "minikube",
- ResourceRequests: corev1.ResourceList{corev1.ResourceMemory: resource.MustParse("128Mi")},
+ ResourceRequests: v1.ResourceList{v1.ResourceMemory: resource.MustParse("128Mi")},
}, info.PodInfo)
assert.Equal(t, &v1alpha1.ResourceNetworkingInfo{Labels: map[string]string{"app": "guestbook"}}, info.NetworkingInfo)
})
@@ -906,8 +907,8 @@ status:
populateNodeInfo(node, info, []string{})
assert.Equal(t, &NodeInfo{
Name: "minikube",
- 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"},
+ 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"},
}, info.NodeInfo)
}
@@ -917,7 +918,7 @@ func TestGetServiceInfo(t *testing.T) {
assert.Empty(t, info.Info)
assert.Equal(t, &v1alpha1.ResourceNetworkingInfo{
TargetLabels: map[string]string{"app": "guestbook"},
- Ingress: []corev1.LoadBalancerIngress{{Hostname: "localhost"}},
+ Ingress: []v1.LoadBalancerIngress{{Hostname: "localhost"}},
}, info.NetworkingInfo)
}
@@ -927,7 +928,7 @@ func TestGetLinkAnnotatedServiceInfo(t *testing.T) {
assert.Empty(t, info.Info)
assert.Equal(t, &v1alpha1.ResourceNetworkingInfo{
TargetLabels: map[string]string{"app": "guestbook"},
- Ingress: []corev1.LoadBalancerIngress{{Hostname: "localhost"}},
+ Ingress: []v1.LoadBalancerIngress{{Hostname: "localhost"}},
ExternalURLs: []string{"http://my-grafana.example.com/pre-generated-link"},
}, info.NetworkingInfo)
}
@@ -985,7 +986,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: []corev1.LoadBalancerIngress{{IP: "107.178.210.11"}},
+ Ingress: []v1.LoadBalancerIngress{{IP: "107.178.210.11"}},
TargetRefs: []v1alpha1.ResourceRef{{
Namespace: "default",
Group: "",
@@ -1010,7 +1011,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: []corev1.LoadBalancerIngress{{IP: "107.178.210.11"}},
+ Ingress: []v1.LoadBalancerIngress{{IP: "107.178.210.11"}},
TargetRefs: []v1alpha1.ResourceRef{{
Namespace: "default",
Group: "",
@@ -1034,7 +1035,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: []corev1.LoadBalancerIngress{{IP: "107.178.210.11"}},
+ Ingress: []v1.LoadBalancerIngress{{IP: "107.178.210.11"}},
TargetRefs: []v1alpha1.ResourceRef{{
Namespace: "default",
Group: "",
@@ -1052,13 +1053,13 @@ func TestGetIngressInfoWildCardPath(t *testing.T) {
func TestGetIngressInfoWithoutTls(t *testing.T) {
info := &ResourceInfo{}
- populateNodeInfo(testIngressWithoutTLS, info, []string{})
+ populateNodeInfo(testIngressWithoutTls, info, []string{})
assert.Empty(t, info.Info)
sort.Slice(info.NetworkingInfo.TargetRefs, func(i, j int) bool {
return strings.Compare(info.NetworkingInfo.TargetRefs[j].Name, info.NetworkingInfo.TargetRefs[i].Name) < 0
})
assert.Equal(t, &v1alpha1.ResourceNetworkingInfo{
- Ingress: []corev1.LoadBalancerIngress{{IP: "107.178.210.11"}},
+ Ingress: []v1.LoadBalancerIngress{{IP: "107.178.210.11"}},
TargetRefs: []v1alpha1.ResourceRef{{
Namespace: "default",
Group: "",
@@ -1100,7 +1101,7 @@ func TestGetIngressInfoWithHost(t *testing.T) {
populateNodeInfo(ingress, info, []string{})
assert.Equal(t, &v1alpha1.ResourceNetworkingInfo{
- Ingress: []corev1.LoadBalancerIngress{{IP: "107.178.210.11"}},
+ Ingress: []v1.LoadBalancerIngress{{IP: "107.178.210.11"}},
TargetRefs: []v1alpha1.ResourceRef{{
Namespace: "default",
Group: "",
diff --git a/controller/cache/mocks/LiveStateCache.go b/controller/cache/mocks/LiveStateCache.go
index 378338c170..f25e8166a5 100644
--- a/controller/cache/mocks/LiveStateCache.go
+++ b/controller/cache/mocks/LiveStateCache.go
@@ -1,21 +1,295 @@
-// Code generated by mockery; DO NOT EDIT.
-// github.com/vektra/mockery
-// template: testify
+// Code generated by mockery v2.53.4. DO NOT EDIT.
package mocks
import (
- "context"
+ context "context"
+
+ cache "github.com/argoproj/gitops-engine/pkg/cache"
+
+ controllercache "github.com/argoproj/argo-cd/v2/controller/cache"
+
+ kube "github.com/argoproj/gitops-engine/pkg/utils/kube"
- cache0 "github.com/argoproj/argo-cd/v3/controller/cache"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- "github.com/argoproj/gitops-engine/pkg/cache"
- "github.com/argoproj/gitops-engine/pkg/utils/kube"
mock "github.com/stretchr/testify/mock"
- "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
- "k8s.io/apimachinery/pkg/runtime/schema"
+
+ schema "k8s.io/apimachinery/pkg/runtime/schema"
+
+ unstructured "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
+
+ v1alpha1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
)
+// LiveStateCache is an autogenerated mock type for the LiveStateCache type
+type LiveStateCache struct {
+ mock.Mock
+}
+
+// GetClusterCache provides a mock function with given fields: server
+func (_m *LiveStateCache) GetClusterCache(server string) (cache.ClusterCache, error) {
+ ret := _m.Called(server)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetClusterCache")
+ }
+
+ var r0 cache.ClusterCache
+ var r1 error
+ if rf, ok := ret.Get(0).(func(string) (cache.ClusterCache, error)); ok {
+ return rf(server)
+ }
+ if rf, ok := ret.Get(0).(func(string) cache.ClusterCache); ok {
+ r0 = rf(server)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(cache.ClusterCache)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(string) error); ok {
+ r1 = rf(server)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetClustersInfo provides a mock function with no fields
+func (_m *LiveStateCache) GetClustersInfo() []cache.ClusterInfo {
+ ret := _m.Called()
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetClustersInfo")
+ }
+
+ var r0 []cache.ClusterInfo
+ if rf, ok := ret.Get(0).(func() []cache.ClusterInfo); ok {
+ r0 = rf()
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).([]cache.ClusterInfo)
+ }
+ }
+
+ return r0
+}
+
+// GetManagedLiveObjs provides a mock function with given fields: a, targetObjs
+func (_m *LiveStateCache) GetManagedLiveObjs(a *v1alpha1.Application, targetObjs []*unstructured.Unstructured) (map[kube.ResourceKey]*unstructured.Unstructured, error) {
+ ret := _m.Called(a, targetObjs)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetManagedLiveObjs")
+ }
+
+ var r0 map[kube.ResourceKey]*unstructured.Unstructured
+ var r1 error
+ if rf, ok := ret.Get(0).(func(*v1alpha1.Application, []*unstructured.Unstructured) (map[kube.ResourceKey]*unstructured.Unstructured, error)); ok {
+ return rf(a, targetObjs)
+ }
+ if rf, ok := ret.Get(0).(func(*v1alpha1.Application, []*unstructured.Unstructured) map[kube.ResourceKey]*unstructured.Unstructured); ok {
+ r0 = rf(a, targetObjs)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(map[kube.ResourceKey]*unstructured.Unstructured)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(*v1alpha1.Application, []*unstructured.Unstructured) error); ok {
+ r1 = rf(a, targetObjs)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetNamespaceTopLevelResources provides a mock function with given fields: server, namespace
+func (_m *LiveStateCache) GetNamespaceTopLevelResources(server string, namespace string) (map[kube.ResourceKey]v1alpha1.ResourceNode, error) {
+ ret := _m.Called(server, namespace)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetNamespaceTopLevelResources")
+ }
+
+ var r0 map[kube.ResourceKey]v1alpha1.ResourceNode
+ var r1 error
+ if rf, ok := ret.Get(0).(func(string, string) (map[kube.ResourceKey]v1alpha1.ResourceNode, error)); ok {
+ return rf(server, namespace)
+ }
+ if rf, ok := ret.Get(0).(func(string, string) map[kube.ResourceKey]v1alpha1.ResourceNode); ok {
+ r0 = rf(server, namespace)
+ } else {
+ if ret.Get(0) != nil {
+ r0 = ret.Get(0).(map[kube.ResourceKey]v1alpha1.ResourceNode)
+ }
+ }
+
+ if rf, ok := ret.Get(1).(func(string, string) error); ok {
+ r1 = rf(server, namespace)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// GetVersionsInfo provides a mock function with given fields: serverURL
+func (_m *LiveStateCache) GetVersionsInfo(serverURL string) (string, []kube.APIResourceInfo, error) {
+ ret := _m.Called(serverURL)
+
+ if len(ret) == 0 {
+ panic("no return value specified for GetVersionsInfo")
+ }
+
+ var r0 string
+ var r1 []kube.APIResourceInfo
+ var r2 error
+ if rf, ok := ret.Get(0).(func(string) (string, []kube.APIResourceInfo, error)); ok {
+ return rf(serverURL)
+ }
+ if rf, ok := ret.Get(0).(func(string) string); ok {
+ r0 = rf(serverURL)
+ } else {
+ r0 = ret.Get(0).(string)
+ }
+
+ if rf, ok := ret.Get(1).(func(string) []kube.APIResourceInfo); ok {
+ r1 = rf(serverURL)
+ } else {
+ if ret.Get(1) != nil {
+ r1 = ret.Get(1).([]kube.APIResourceInfo)
+ }
+ }
+
+ if rf, ok := ret.Get(2).(func(string) error); ok {
+ r2 = rf(serverURL)
+ } else {
+ r2 = ret.Error(2)
+ }
+
+ return r0, r1, r2
+}
+
+// Init provides a mock function with no fields
+func (_m *LiveStateCache) Init() error {
+ ret := _m.Called()
+
+ if len(ret) == 0 {
+ panic("no return value specified for Init")
+ }
+
+ var r0 error
+ if rf, ok := ret.Get(0).(func() error); ok {
+ r0 = rf()
+ } else {
+ r0 = ret.Error(0)
+ }
+
+ return r0
+}
+
+// IsNamespaced provides a mock function with given fields: server, gk
+func (_m *LiveStateCache) IsNamespaced(server string, gk schema.GroupKind) (bool, error) {
+ ret := _m.Called(server, gk)
+
+ if len(ret) == 0 {
+ panic("no return value specified for IsNamespaced")
+ }
+
+ var r0 bool
+ var r1 error
+ if rf, ok := ret.Get(0).(func(string, schema.GroupKind) (bool, error)); ok {
+ return rf(server, gk)
+ }
+ if rf, ok := ret.Get(0).(func(string, schema.GroupKind) bool); ok {
+ r0 = rf(server, gk)
+ } else {
+ r0 = ret.Get(0).(bool)
+ }
+
+ if rf, ok := ret.Get(1).(func(string, schema.GroupKind) error); ok {
+ r1 = rf(server, gk)
+ } else {
+ r1 = ret.Error(1)
+ }
+
+ return r0, r1
+}
+
+// IterateHierarchy provides a mock function with given fields: server, key, action
+func (_m *LiveStateCache) IterateHierarchy(server string, key kube.ResourceKey, action func(v1alpha1.ResourceNode, string) bool) error {
+ ret := _m.Called(server, key, action)
+
+ if len(ret) == 0 {
+ panic("no return value specified for IterateHierarchy")
+ }
+
+ var r0 error
+ if rf, ok := ret.Get(0).(func(string, kube.ResourceKey, func(v1alpha1.ResourceNode, string) bool) error); ok {
+ r0 = rf(server, key, action)
+ } else {
+ r0 = ret.Error(0)
+ }
+
+ return r0
+}
+
+// IterateHierarchyV2 provides a mock function with given fields: server, keys, action
+func (_m *LiveStateCache) IterateHierarchyV2(server string, keys []kube.ResourceKey, action func(v1alpha1.ResourceNode, string) bool) error {
+ ret := _m.Called(server, keys, action)
+
+ if len(ret) == 0 {
+ panic("no return value specified for IterateHierarchyV2")
+ }
+
+ var r0 error
+ if rf, ok := ret.Get(0).(func(string, []kube.ResourceKey, func(v1alpha1.ResourceNode, string) bool) error); ok {
+ r0 = rf(server, keys, action)
+ } else {
+ r0 = ret.Error(0)
+ }
+
+ return r0
+}
+
+// IterateResources provides a mock function with given fields: server, callback
+func (_m *LiveStateCache) IterateResources(server string, callback func(*cache.Resource, *controllercache.ResourceInfo)) error {
+ ret := _m.Called(server, callback)
+
+ if len(ret) == 0 {
+ panic("no return value specified for IterateResources")
+ }
+
+ var r0 error
+ if rf, ok := ret.Get(0).(func(string, func(*cache.Resource, *controllercache.ResourceInfo)) error); ok {
+ r0 = rf(server, callback)
+ } else {
+ r0 = ret.Error(0)
+ }
+
+ return r0
+}
+
+// Run provides a mock function with given fields: ctx
+func (_m *LiveStateCache) Run(ctx context.Context) error {
+ ret := _m.Called(ctx)
+
+ if len(ret) == 0 {
+ panic("no return value specified for Run")
+ }
+
+ var r0 error
+ if rf, ok := ret.Get(0).(func(context.Context) error); ok {
+ r0 = rf(ctx)
+ } else {
+ r0 = ret.Error(0)
+ }
+
+ return r0
+}
+
// NewLiveStateCache creates a new instance of LiveStateCache. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
// The first argument is typically a *testing.T value.
func NewLiveStateCache(t interface {
@@ -29,624 +303,3 @@ func NewLiveStateCache(t interface {
return mock
}
-
-// LiveStateCache is an autogenerated mock type for the LiveStateCache type
-type LiveStateCache struct {
- mock.Mock
-}
-
-type LiveStateCache_Expecter struct {
- mock *mock.Mock
-}
-
-func (_m *LiveStateCache) EXPECT() *LiveStateCache_Expecter {
- return &LiveStateCache_Expecter{mock: &_m.Mock}
-}
-
-// GetClusterCache provides a mock function for the type LiveStateCache
-func (_mock *LiveStateCache) GetClusterCache(server *v1alpha1.Cluster) (cache.ClusterCache, error) {
- ret := _mock.Called(server)
-
- if len(ret) == 0 {
- panic("no return value specified for GetClusterCache")
- }
-
- var r0 cache.ClusterCache
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(*v1alpha1.Cluster) (cache.ClusterCache, error)); ok {
- return returnFunc(server)
- }
- if returnFunc, ok := ret.Get(0).(func(*v1alpha1.Cluster) cache.ClusterCache); ok {
- r0 = returnFunc(server)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(cache.ClusterCache)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(*v1alpha1.Cluster) error); ok {
- r1 = returnFunc(server)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// LiveStateCache_GetClusterCache_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetClusterCache'
-type LiveStateCache_GetClusterCache_Call struct {
- *mock.Call
-}
-
-// GetClusterCache is a helper method to define mock.On call
-// - server
-func (_e *LiveStateCache_Expecter) GetClusterCache(server interface{}) *LiveStateCache_GetClusterCache_Call {
- return &LiveStateCache_GetClusterCache_Call{Call: _e.mock.On("GetClusterCache", server)}
-}
-
-func (_c *LiveStateCache_GetClusterCache_Call) Run(run func(server *v1alpha1.Cluster)) *LiveStateCache_GetClusterCache_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(*v1alpha1.Cluster))
- })
- return _c
-}
-
-func (_c *LiveStateCache_GetClusterCache_Call) Return(clusterCache cache.ClusterCache, err error) *LiveStateCache_GetClusterCache_Call {
- _c.Call.Return(clusterCache, err)
- return _c
-}
-
-func (_c *LiveStateCache_GetClusterCache_Call) RunAndReturn(run func(server *v1alpha1.Cluster) (cache.ClusterCache, error)) *LiveStateCache_GetClusterCache_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetClustersInfo provides a mock function for the type LiveStateCache
-func (_mock *LiveStateCache) GetClustersInfo() []cache.ClusterInfo {
- ret := _mock.Called()
-
- if len(ret) == 0 {
- panic("no return value specified for GetClustersInfo")
- }
-
- var r0 []cache.ClusterInfo
- if returnFunc, ok := ret.Get(0).(func() []cache.ClusterInfo); ok {
- r0 = returnFunc()
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).([]cache.ClusterInfo)
- }
- }
- return r0
-}
-
-// LiveStateCache_GetClustersInfo_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetClustersInfo'
-type LiveStateCache_GetClustersInfo_Call struct {
- *mock.Call
-}
-
-// GetClustersInfo is a helper method to define mock.On call
-func (_e *LiveStateCache_Expecter) GetClustersInfo() *LiveStateCache_GetClustersInfo_Call {
- return &LiveStateCache_GetClustersInfo_Call{Call: _e.mock.On("GetClustersInfo")}
-}
-
-func (_c *LiveStateCache_GetClustersInfo_Call) Run(run func()) *LiveStateCache_GetClustersInfo_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run()
- })
- return _c
-}
-
-func (_c *LiveStateCache_GetClustersInfo_Call) Return(clusterInfos []cache.ClusterInfo) *LiveStateCache_GetClustersInfo_Call {
- _c.Call.Return(clusterInfos)
- return _c
-}
-
-func (_c *LiveStateCache_GetClustersInfo_Call) RunAndReturn(run func() []cache.ClusterInfo) *LiveStateCache_GetClustersInfo_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetManagedLiveObjs provides a mock function for the type LiveStateCache
-func (_mock *LiveStateCache) GetManagedLiveObjs(destCluster *v1alpha1.Cluster, a *v1alpha1.Application, targetObjs []*unstructured.Unstructured) (map[kube.ResourceKey]*unstructured.Unstructured, error) {
- ret := _mock.Called(destCluster, a, targetObjs)
-
- if len(ret) == 0 {
- panic("no return value specified for GetManagedLiveObjs")
- }
-
- var r0 map[kube.ResourceKey]*unstructured.Unstructured
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(*v1alpha1.Cluster, *v1alpha1.Application, []*unstructured.Unstructured) (map[kube.ResourceKey]*unstructured.Unstructured, error)); ok {
- return returnFunc(destCluster, a, targetObjs)
- }
- if returnFunc, ok := ret.Get(0).(func(*v1alpha1.Cluster, *v1alpha1.Application, []*unstructured.Unstructured) map[kube.ResourceKey]*unstructured.Unstructured); ok {
- r0 = returnFunc(destCluster, a, targetObjs)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(map[kube.ResourceKey]*unstructured.Unstructured)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(*v1alpha1.Cluster, *v1alpha1.Application, []*unstructured.Unstructured) error); ok {
- r1 = returnFunc(destCluster, a, targetObjs)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// LiveStateCache_GetManagedLiveObjs_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetManagedLiveObjs'
-type LiveStateCache_GetManagedLiveObjs_Call struct {
- *mock.Call
-}
-
-// GetManagedLiveObjs is a helper method to define mock.On call
-// - destCluster
-// - a
-// - targetObjs
-func (_e *LiveStateCache_Expecter) GetManagedLiveObjs(destCluster interface{}, a interface{}, targetObjs interface{}) *LiveStateCache_GetManagedLiveObjs_Call {
- return &LiveStateCache_GetManagedLiveObjs_Call{Call: _e.mock.On("GetManagedLiveObjs", destCluster, a, targetObjs)}
-}
-
-func (_c *LiveStateCache_GetManagedLiveObjs_Call) Run(run func(destCluster *v1alpha1.Cluster, a *v1alpha1.Application, targetObjs []*unstructured.Unstructured)) *LiveStateCache_GetManagedLiveObjs_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(*v1alpha1.Cluster), args[1].(*v1alpha1.Application), args[2].([]*unstructured.Unstructured))
- })
- return _c
-}
-
-func (_c *LiveStateCache_GetManagedLiveObjs_Call) Return(resourceKeyToUnstructured map[kube.ResourceKey]*unstructured.Unstructured, err error) *LiveStateCache_GetManagedLiveObjs_Call {
- _c.Call.Return(resourceKeyToUnstructured, err)
- return _c
-}
-
-func (_c *LiveStateCache_GetManagedLiveObjs_Call) RunAndReturn(run func(destCluster *v1alpha1.Cluster, a *v1alpha1.Application, targetObjs []*unstructured.Unstructured) (map[kube.ResourceKey]*unstructured.Unstructured, error)) *LiveStateCache_GetManagedLiveObjs_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetNamespaceTopLevelResources provides a mock function for the type LiveStateCache
-func (_mock *LiveStateCache) GetNamespaceTopLevelResources(server *v1alpha1.Cluster, namespace string) (map[kube.ResourceKey]v1alpha1.ResourceNode, error) {
- ret := _mock.Called(server, namespace)
-
- if len(ret) == 0 {
- panic("no return value specified for GetNamespaceTopLevelResources")
- }
-
- var r0 map[kube.ResourceKey]v1alpha1.ResourceNode
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(*v1alpha1.Cluster, string) (map[kube.ResourceKey]v1alpha1.ResourceNode, error)); ok {
- return returnFunc(server, namespace)
- }
- if returnFunc, ok := ret.Get(0).(func(*v1alpha1.Cluster, string) map[kube.ResourceKey]v1alpha1.ResourceNode); ok {
- r0 = returnFunc(server, namespace)
- } else {
- if ret.Get(0) != nil {
- r0 = ret.Get(0).(map[kube.ResourceKey]v1alpha1.ResourceNode)
- }
- }
- if returnFunc, ok := ret.Get(1).(func(*v1alpha1.Cluster, string) error); ok {
- r1 = returnFunc(server, namespace)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// LiveStateCache_GetNamespaceTopLevelResources_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetNamespaceTopLevelResources'
-type LiveStateCache_GetNamespaceTopLevelResources_Call struct {
- *mock.Call
-}
-
-// GetNamespaceTopLevelResources is a helper method to define mock.On call
-// - server
-// - namespace
-func (_e *LiveStateCache_Expecter) GetNamespaceTopLevelResources(server interface{}, namespace interface{}) *LiveStateCache_GetNamespaceTopLevelResources_Call {
- return &LiveStateCache_GetNamespaceTopLevelResources_Call{Call: _e.mock.On("GetNamespaceTopLevelResources", server, namespace)}
-}
-
-func (_c *LiveStateCache_GetNamespaceTopLevelResources_Call) Run(run func(server *v1alpha1.Cluster, namespace string)) *LiveStateCache_GetNamespaceTopLevelResources_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(*v1alpha1.Cluster), args[1].(string))
- })
- return _c
-}
-
-func (_c *LiveStateCache_GetNamespaceTopLevelResources_Call) Return(resourceKeyToResourceNode map[kube.ResourceKey]v1alpha1.ResourceNode, err error) *LiveStateCache_GetNamespaceTopLevelResources_Call {
- _c.Call.Return(resourceKeyToResourceNode, err)
- return _c
-}
-
-func (_c *LiveStateCache_GetNamespaceTopLevelResources_Call) RunAndReturn(run func(server *v1alpha1.Cluster, namespace string) (map[kube.ResourceKey]v1alpha1.ResourceNode, error)) *LiveStateCache_GetNamespaceTopLevelResources_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// GetVersionsInfo provides a mock function for the type LiveStateCache
-func (_mock *LiveStateCache) GetVersionsInfo(server *v1alpha1.Cluster) (string, []kube.APIResourceInfo, error) {
- ret := _mock.Called(server)
-
- if len(ret) == 0 {
- panic("no return value specified for GetVersionsInfo")
- }
-
- var r0 string
- var r1 []kube.APIResourceInfo
- var r2 error
- if returnFunc, ok := ret.Get(0).(func(*v1alpha1.Cluster) (string, []kube.APIResourceInfo, error)); ok {
- return returnFunc(server)
- }
- if returnFunc, ok := ret.Get(0).(func(*v1alpha1.Cluster) string); ok {
- r0 = returnFunc(server)
- } else {
- r0 = ret.Get(0).(string)
- }
- if returnFunc, ok := ret.Get(1).(func(*v1alpha1.Cluster) []kube.APIResourceInfo); ok {
- r1 = returnFunc(server)
- } else {
- if ret.Get(1) != nil {
- r1 = ret.Get(1).([]kube.APIResourceInfo)
- }
- }
- if returnFunc, ok := ret.Get(2).(func(*v1alpha1.Cluster) error); ok {
- r2 = returnFunc(server)
- } else {
- r2 = ret.Error(2)
- }
- return r0, r1, r2
-}
-
-// LiveStateCache_GetVersionsInfo_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetVersionsInfo'
-type LiveStateCache_GetVersionsInfo_Call struct {
- *mock.Call
-}
-
-// GetVersionsInfo is a helper method to define mock.On call
-// - server
-func (_e *LiveStateCache_Expecter) GetVersionsInfo(server interface{}) *LiveStateCache_GetVersionsInfo_Call {
- return &LiveStateCache_GetVersionsInfo_Call{Call: _e.mock.On("GetVersionsInfo", server)}
-}
-
-func (_c *LiveStateCache_GetVersionsInfo_Call) Run(run func(server *v1alpha1.Cluster)) *LiveStateCache_GetVersionsInfo_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(*v1alpha1.Cluster))
- })
- return _c
-}
-
-func (_c *LiveStateCache_GetVersionsInfo_Call) Return(s string, aPIResourceInfos []kube.APIResourceInfo, err error) *LiveStateCache_GetVersionsInfo_Call {
- _c.Call.Return(s, aPIResourceInfos, err)
- return _c
-}
-
-func (_c *LiveStateCache_GetVersionsInfo_Call) RunAndReturn(run func(server *v1alpha1.Cluster) (string, []kube.APIResourceInfo, error)) *LiveStateCache_GetVersionsInfo_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// Init provides a mock function for the type LiveStateCache
-func (_mock *LiveStateCache) Init() error {
- ret := _mock.Called()
-
- if len(ret) == 0 {
- panic("no return value specified for Init")
- }
-
- var r0 error
- if returnFunc, ok := ret.Get(0).(func() error); ok {
- r0 = returnFunc()
- } else {
- r0 = ret.Error(0)
- }
- return r0
-}
-
-// LiveStateCache_Init_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Init'
-type LiveStateCache_Init_Call struct {
- *mock.Call
-}
-
-// Init is a helper method to define mock.On call
-func (_e *LiveStateCache_Expecter) Init() *LiveStateCache_Init_Call {
- return &LiveStateCache_Init_Call{Call: _e.mock.On("Init")}
-}
-
-func (_c *LiveStateCache_Init_Call) Run(run func()) *LiveStateCache_Init_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run()
- })
- return _c
-}
-
-func (_c *LiveStateCache_Init_Call) Return(err error) *LiveStateCache_Init_Call {
- _c.Call.Return(err)
- return _c
-}
-
-func (_c *LiveStateCache_Init_Call) RunAndReturn(run func() error) *LiveStateCache_Init_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// IsNamespaced provides a mock function for the type LiveStateCache
-func (_mock *LiveStateCache) IsNamespaced(server *v1alpha1.Cluster, gk schema.GroupKind) (bool, error) {
- ret := _mock.Called(server, gk)
-
- if len(ret) == 0 {
- panic("no return value specified for IsNamespaced")
- }
-
- var r0 bool
- var r1 error
- if returnFunc, ok := ret.Get(0).(func(*v1alpha1.Cluster, schema.GroupKind) (bool, error)); ok {
- return returnFunc(server, gk)
- }
- if returnFunc, ok := ret.Get(0).(func(*v1alpha1.Cluster, schema.GroupKind) bool); ok {
- r0 = returnFunc(server, gk)
- } else {
- r0 = ret.Get(0).(bool)
- }
- if returnFunc, ok := ret.Get(1).(func(*v1alpha1.Cluster, schema.GroupKind) error); ok {
- r1 = returnFunc(server, gk)
- } else {
- r1 = ret.Error(1)
- }
- return r0, r1
-}
-
-// LiveStateCache_IsNamespaced_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'IsNamespaced'
-type LiveStateCache_IsNamespaced_Call struct {
- *mock.Call
-}
-
-// IsNamespaced is a helper method to define mock.On call
-// - server
-// - gk
-func (_e *LiveStateCache_Expecter) IsNamespaced(server interface{}, gk interface{}) *LiveStateCache_IsNamespaced_Call {
- return &LiveStateCache_IsNamespaced_Call{Call: _e.mock.On("IsNamespaced", server, gk)}
-}
-
-func (_c *LiveStateCache_IsNamespaced_Call) Run(run func(server *v1alpha1.Cluster, gk schema.GroupKind)) *LiveStateCache_IsNamespaced_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(*v1alpha1.Cluster), args[1].(schema.GroupKind))
- })
- return _c
-}
-
-func (_c *LiveStateCache_IsNamespaced_Call) Return(b bool, err error) *LiveStateCache_IsNamespaced_Call {
- _c.Call.Return(b, err)
- return _c
-}
-
-func (_c *LiveStateCache_IsNamespaced_Call) RunAndReturn(run func(server *v1alpha1.Cluster, gk schema.GroupKind) (bool, error)) *LiveStateCache_IsNamespaced_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// IterateHierarchy provides a mock function for the type LiveStateCache
-func (_mock *LiveStateCache) IterateHierarchy(server *v1alpha1.Cluster, key kube.ResourceKey, action func(child v1alpha1.ResourceNode, appName string) bool) error {
- ret := _mock.Called(server, key, action)
-
- if len(ret) == 0 {
- panic("no return value specified for IterateHierarchy")
- }
-
- var r0 error
- if returnFunc, ok := ret.Get(0).(func(*v1alpha1.Cluster, kube.ResourceKey, func(child v1alpha1.ResourceNode, appName string) bool) error); ok {
- r0 = returnFunc(server, key, action)
- } else {
- r0 = ret.Error(0)
- }
- return r0
-}
-
-// LiveStateCache_IterateHierarchy_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'IterateHierarchy'
-type LiveStateCache_IterateHierarchy_Call struct {
- *mock.Call
-}
-
-// IterateHierarchy is a helper method to define mock.On call
-// - server
-// - key
-// - action
-func (_e *LiveStateCache_Expecter) IterateHierarchy(server interface{}, key interface{}, action interface{}) *LiveStateCache_IterateHierarchy_Call {
- return &LiveStateCache_IterateHierarchy_Call{Call: _e.mock.On("IterateHierarchy", server, key, action)}
-}
-
-func (_c *LiveStateCache_IterateHierarchy_Call) Run(run func(server *v1alpha1.Cluster, key kube.ResourceKey, action func(child v1alpha1.ResourceNode, appName string) bool)) *LiveStateCache_IterateHierarchy_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(*v1alpha1.Cluster), args[1].(kube.ResourceKey), args[2].(func(child v1alpha1.ResourceNode, appName string) bool))
- })
- return _c
-}
-
-func (_c *LiveStateCache_IterateHierarchy_Call) Return(err error) *LiveStateCache_IterateHierarchy_Call {
- _c.Call.Return(err)
- return _c
-}
-
-func (_c *LiveStateCache_IterateHierarchy_Call) RunAndReturn(run func(server *v1alpha1.Cluster, key kube.ResourceKey, action func(child v1alpha1.ResourceNode, appName string) bool) error) *LiveStateCache_IterateHierarchy_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// IterateHierarchyV2 provides a mock function for the type LiveStateCache
-func (_mock *LiveStateCache) IterateHierarchyV2(server *v1alpha1.Cluster, keys []kube.ResourceKey, action func(child v1alpha1.ResourceNode, appName string) bool) error {
- ret := _mock.Called(server, keys, action)
-
- if len(ret) == 0 {
- panic("no return value specified for IterateHierarchyV2")
- }
-
- var r0 error
- if returnFunc, ok := ret.Get(0).(func(*v1alpha1.Cluster, []kube.ResourceKey, func(child v1alpha1.ResourceNode, appName string) bool) error); ok {
- r0 = returnFunc(server, keys, action)
- } else {
- r0 = ret.Error(0)
- }
- return r0
-}
-
-// LiveStateCache_IterateHierarchyV2_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'IterateHierarchyV2'
-type LiveStateCache_IterateHierarchyV2_Call struct {
- *mock.Call
-}
-
-// IterateHierarchyV2 is a helper method to define mock.On call
-// - server
-// - keys
-// - action
-func (_e *LiveStateCache_Expecter) IterateHierarchyV2(server interface{}, keys interface{}, action interface{}) *LiveStateCache_IterateHierarchyV2_Call {
- return &LiveStateCache_IterateHierarchyV2_Call{Call: _e.mock.On("IterateHierarchyV2", server, keys, action)}
-}
-
-func (_c *LiveStateCache_IterateHierarchyV2_Call) Run(run func(server *v1alpha1.Cluster, keys []kube.ResourceKey, action func(child v1alpha1.ResourceNode, appName string) bool)) *LiveStateCache_IterateHierarchyV2_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(*v1alpha1.Cluster), args[1].([]kube.ResourceKey), args[2].(func(child v1alpha1.ResourceNode, appName string) bool))
- })
- return _c
-}
-
-func (_c *LiveStateCache_IterateHierarchyV2_Call) Return(err error) *LiveStateCache_IterateHierarchyV2_Call {
- _c.Call.Return(err)
- return _c
-}
-
-func (_c *LiveStateCache_IterateHierarchyV2_Call) RunAndReturn(run func(server *v1alpha1.Cluster, keys []kube.ResourceKey, action func(child v1alpha1.ResourceNode, appName string) bool) error) *LiveStateCache_IterateHierarchyV2_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// IterateResources provides a mock function for the type LiveStateCache
-func (_mock *LiveStateCache) IterateResources(server *v1alpha1.Cluster, callback func(res *cache.Resource, info *cache0.ResourceInfo)) error {
- ret := _mock.Called(server, callback)
-
- if len(ret) == 0 {
- panic("no return value specified for IterateResources")
- }
-
- var r0 error
- if returnFunc, ok := ret.Get(0).(func(*v1alpha1.Cluster, func(res *cache.Resource, info *cache0.ResourceInfo)) error); ok {
- r0 = returnFunc(server, callback)
- } else {
- r0 = ret.Error(0)
- }
- return r0
-}
-
-// LiveStateCache_IterateResources_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'IterateResources'
-type LiveStateCache_IterateResources_Call struct {
- *mock.Call
-}
-
-// IterateResources is a helper method to define mock.On call
-// - server
-// - callback
-func (_e *LiveStateCache_Expecter) IterateResources(server interface{}, callback interface{}) *LiveStateCache_IterateResources_Call {
- return &LiveStateCache_IterateResources_Call{Call: _e.mock.On("IterateResources", server, callback)}
-}
-
-func (_c *LiveStateCache_IterateResources_Call) Run(run func(server *v1alpha1.Cluster, callback func(res *cache.Resource, info *cache0.ResourceInfo))) *LiveStateCache_IterateResources_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(*v1alpha1.Cluster), args[1].(func(res *cache.Resource, info *cache0.ResourceInfo)))
- })
- return _c
-}
-
-func (_c *LiveStateCache_IterateResources_Call) Return(err error) *LiveStateCache_IterateResources_Call {
- _c.Call.Return(err)
- return _c
-}
-
-func (_c *LiveStateCache_IterateResources_Call) RunAndReturn(run func(server *v1alpha1.Cluster, callback func(res *cache.Resource, info *cache0.ResourceInfo)) error) *LiveStateCache_IterateResources_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// Run provides a mock function for the type LiveStateCache
-func (_mock *LiveStateCache) Run(ctx context.Context) error {
- ret := _mock.Called(ctx)
-
- if len(ret) == 0 {
- panic("no return value specified for Run")
- }
-
- var r0 error
- if returnFunc, ok := ret.Get(0).(func(context.Context) error); ok {
- r0 = returnFunc(ctx)
- } else {
- r0 = ret.Error(0)
- }
- return r0
-}
-
-// LiveStateCache_Run_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Run'
-type LiveStateCache_Run_Call struct {
- *mock.Call
-}
-
-// Run is a helper method to define mock.On call
-// - ctx
-func (_e *LiveStateCache_Expecter) Run(ctx interface{}) *LiveStateCache_Run_Call {
- return &LiveStateCache_Run_Call{Call: _e.mock.On("Run", ctx)}
-}
-
-func (_c *LiveStateCache_Run_Call) Run(run func(ctx context.Context)) *LiveStateCache_Run_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(context.Context))
- })
- return _c
-}
-
-func (_c *LiveStateCache_Run_Call) Return(err error) *LiveStateCache_Run_Call {
- _c.Call.Return(err)
- return _c
-}
-
-func (_c *LiveStateCache_Run_Call) RunAndReturn(run func(ctx context.Context) error) *LiveStateCache_Run_Call {
- _c.Call.Return(run)
- return _c
-}
-
-// UpdateShard provides a mock function for the type LiveStateCache
-func (_mock *LiveStateCache) UpdateShard(shard int) bool {
- ret := _mock.Called(shard)
-
- if len(ret) == 0 {
- panic("no return value specified for UpdateShard")
- }
-
- var r0 bool
- if returnFunc, ok := ret.Get(0).(func(int) bool); ok {
- r0 = returnFunc(shard)
- } else {
- r0 = ret.Get(0).(bool)
- }
- return r0
-}
-
-// LiveStateCache_UpdateShard_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UpdateShard'
-type LiveStateCache_UpdateShard_Call struct {
- *mock.Call
-}
-
-// UpdateShard is a helper method to define mock.On call
-// - shard
-func (_e *LiveStateCache_Expecter) UpdateShard(shard interface{}) *LiveStateCache_UpdateShard_Call {
- return &LiveStateCache_UpdateShard_Call{Call: _e.mock.On("UpdateShard", shard)}
-}
-
-func (_c *LiveStateCache_UpdateShard_Call) Run(run func(shard int)) *LiveStateCache_UpdateShard_Call {
- _c.Call.Run(func(args mock.Arguments) {
- run(args[0].(int))
- })
- return _c
-}
-
-func (_c *LiveStateCache_UpdateShard_Call) Return(b bool) *LiveStateCache_UpdateShard_Call {
- _c.Call.Return(b)
- return _c
-}
-
-func (_c *LiveStateCache_UpdateShard_Call) RunAndReturn(run func(shard int) bool) *LiveStateCache_UpdateShard_Call {
- _c.Call.Return(run)
- return _c
-}
diff --git a/controller/clusterinfoupdater.go b/controller/clusterinfoupdater.go
index 65f4aed596..655ff6a59b 100644
--- a/controller/clusterinfoupdater.go
+++ b/controller/clusterinfoupdater.go
@@ -5,7 +5,7 @@ import (
"fmt"
"time"
- "github.com/argoproj/argo-cd/v3/common"
+ "github.com/argoproj/argo-cd/v2/common"
"github.com/argoproj/gitops-engine/pkg/cache"
"github.com/argoproj/gitops-engine/pkg/utils/kube"
@@ -13,14 +13,14 @@ import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
- "github.com/argoproj/argo-cd/v3/util/env"
+ "github.com/argoproj/argo-cd/v2/util/env"
- "github.com/argoproj/argo-cd/v3/controller/metrics"
- appv1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- "github.com/argoproj/argo-cd/v3/pkg/client/listers/application/v1alpha1"
- "github.com/argoproj/argo-cd/v3/util/argo"
- appstatecache "github.com/argoproj/argo-cd/v3/util/cache/appstate"
- "github.com/argoproj/argo-cd/v3/util/db"
+ "github.com/argoproj/argo-cd/v2/controller/metrics"
+ appv1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/pkg/client/listers/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/util/argo"
+ appstatecache "github.com/argoproj/argo-cd/v2/util/cache/appstate"
+ "github.com/argoproj/argo-cd/v2/util/db"
)
const (
@@ -132,12 +132,11 @@ func (c *clusterInfoUpdater) getUpdatedClusterInfo(ctx context.Context, apps []*
continue
}
}
- destCluster, err := argo.GetDestinationCluster(ctx, a.Spec.Destination, c.db)
- if err != nil {
+ if err := argo.ValidateDestination(ctx, &a.Spec.Destination, c.db); err != nil {
continue
}
- if destCluster.Server == cluster.Server {
- appCount++
+ if a.Spec.Destination.Server == cluster.Server {
+ appCount += 1
}
}
clusterInfo := appv1.ClusterInfo{
@@ -147,16 +146,15 @@ func (c *clusterInfoUpdater) getUpdatedClusterInfo(ctx context.Context, apps []*
if info != nil {
clusterInfo.ServerVersion = info.K8SVersion
clusterInfo.APIVersions = argo.APIResourcesToStrings(info.APIResources, true)
- switch {
- case info.LastCacheSyncTime == nil:
+ if info.LastCacheSyncTime == nil {
clusterInfo.ConnectionState.Status = appv1.ConnectionStatusUnknown
- case info.SyncError == nil:
+ } else if info.SyncError == nil {
clusterInfo.ConnectionState.Status = appv1.ConnectionStatusSuccessful
syncTime := metav1.NewTime(*info.LastCacheSyncTime)
clusterInfo.CacheInfo.LastCacheSyncTime = &syncTime
clusterInfo.CacheInfo.APIsCount = int64(info.APIsCount)
clusterInfo.CacheInfo.ResourcesCount = int64(info.ResourcesCount)
- default:
+ } else {
clusterInfo.ConnectionState.Status = appv1.ConnectionStatusFailed
clusterInfo.ConnectionState.Message = info.SyncError.Error()
}
diff --git a/controller/clusterinfoupdater_test.go b/controller/clusterinfoupdater_test.go
index 8c66e1ce13..6dc10d9db3 100644
--- a/controller/clusterinfoupdater_test.go
+++ b/controller/clusterinfoupdater_test.go
@@ -7,19 +7,19 @@ import (
"testing"
"time"
- corev1 "k8s.io/api/core/v1"
+ v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
- "github.com/argoproj/argo-cd/v3/common"
+ "github.com/argoproj/argo-cd/v2/common"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- appsfake "github.com/argoproj/argo-cd/v3/pkg/client/clientset/versioned/fake"
- appinformers "github.com/argoproj/argo-cd/v3/pkg/client/informers/externalversions/application/v1alpha1"
- applisters "github.com/argoproj/argo-cd/v3/pkg/client/listers/application/v1alpha1"
- cacheutil "github.com/argoproj/argo-cd/v3/util/cache"
- "github.com/argoproj/argo-cd/v3/util/cache/appstate"
- "github.com/argoproj/argo-cd/v3/util/db"
- "github.com/argoproj/argo-cd/v3/util/settings"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+ appsfake "github.com/argoproj/argo-cd/v2/pkg/client/clientset/versioned/fake"
+ appinformers "github.com/argoproj/argo-cd/v2/pkg/client/informers/externalversions/application/v1alpha1"
+ applisters "github.com/argoproj/argo-cd/v2/pkg/client/listers/application/v1alpha1"
+ 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/settings"
clustercache "github.com/argoproj/gitops-engine/pkg/cache"
"github.com/stretchr/testify/assert"
@@ -41,10 +41,10 @@ func TestClusterSecretUpdater(t *testing.T) {
}{
{nil, nil, v1alpha1.ConnectionStatusUnknown},
{&now, nil, v1alpha1.ConnectionStatusSuccessful},
- {&now, errors.New("sync failed"), v1alpha1.ConnectionStatusFailed},
+ {&now, fmt.Errorf("sync failed"), v1alpha1.ConnectionStatusFailed},
}
- emptyArgoCDConfigMap := &corev1.ConfigMap{
+ emptyArgoCDConfigMap := &v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: common.ArgoCDConfigMapName,
Namespace: fakeNamespace,
@@ -54,7 +54,7 @@ func TestClusterSecretUpdater(t *testing.T) {
},
Data: map[string]string{},
}
- argoCDSecret := &corev1.Secret{
+ argoCDSecret := &v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: common.ArgoCDSecretName,
Namespace: fakeNamespace,
@@ -70,9 +70,9 @@ func TestClusterSecretUpdater(t *testing.T) {
kubeclientset := fake.NewClientset(emptyArgoCDConfigMap, argoCDSecret)
appclientset := appsfake.NewSimpleClientset()
appInformer := appinformers.NewApplicationInformer(appclientset, "", time.Minute, cache.Indexers{})
- settingsManager := settings.NewSettingsManager(t.Context(), kubeclientset, fakeNamespace)
+ settingsManager := settings.NewSettingsManager(context.Background(), kubeclientset, fakeNamespace)
argoDB := db.NewDB(fakeNamespace, settingsManager, kubeclientset)
- ctx, cancel := context.WithCancel(t.Context())
+ ctx, cancel := context.WithCancel(context.Background())
defer cancel()
appCache := appstate.NewCache(cacheutil.NewCache(cacheutil.NewInMemoryCache(time.Minute)), time.Minute)
@@ -90,7 +90,7 @@ func TestClusterSecretUpdater(t *testing.T) {
lister := applisters.NewApplicationLister(appInformer.GetIndexer()).Applications(fakeNamespace)
updater := NewClusterInfoUpdater(nil, argoDB, lister, appCache, nil, nil, fakeNamespace)
- err = updater.updateClusterInfo(t.Context(), *cluster, info)
+ err = updater.updateClusterInfo(context.Background(), *cluster, info)
require.NoError(t, err, "Invoking updateClusterInfo failed.")
var clusterInfo v1alpha1.ClusterInfo
@@ -102,7 +102,7 @@ func TestClusterSecretUpdater(t *testing.T) {
}
func TestUpdateClusterLabels(t *testing.T) {
- shouldNotBeInvoked := func(_ context.Context, _ *v1alpha1.Cluster) (*v1alpha1.Cluster, error) {
+ shouldNotBeInvoked := func(ctx context.Context, cluster *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(_ context.Context, cluster *v1alpha1.Cluster) (*v1alpha1.Cluster, error) {
+ func(ctx 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(_ context.Context, cluster *v1alpha1.Cluster) (*v1alpha1.Cluster, error) {
+ func(ctx 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")
},
@@ -185,7 +185,7 @@ func TestUpdateClusterLabels(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- tt.wantErr(t, updateClusterLabels(t.Context(), tt.clusterInfo, tt.cluster, tt.updateCluster), fmt.Sprintf("updateClusterLabels(%v, %v, %v)", t.Context(), tt.clusterInfo, tt.cluster))
+ tt.wantErr(t, updateClusterLabels(context.Background(), tt.clusterInfo, tt.cluster, tt.updateCluster), fmt.Sprintf("updateClusterLabels(%v, %v, %v)", context.Background(), tt.clusterInfo, tt.cluster))
})
}
}
diff --git a/controller/health.go b/controller/health.go
index ba2270629d..81bdcb06f1 100644
--- a/controller/health.go
+++ b/controller/health.go
@@ -10,19 +10,20 @@ import (
log "github.com/sirupsen/logrus"
"k8s.io/apimachinery/pkg/runtime/schema"
- "github.com/argoproj/argo-cd/v3/common"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application"
- appv1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- applog "github.com/argoproj/argo-cd/v3/util/app/log"
- "github.com/argoproj/argo-cd/v3/util/lua"
+ "github.com/argoproj/argo-cd/v2/common"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application"
+ appv1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/util/lua"
)
// setApplicationHealth updates the health statuses of all resources performed in the comparison
-func setApplicationHealth(resources []managedResource, statuses []appv1.ResourceStatus, resourceOverrides map[string]appv1.ResourceOverride, app *appv1.Application, persistResourceHealth bool) (health.HealthStatusCode, error) {
+func setApplicationHealth(resources []managedResource, statuses []appv1.ResourceStatus, resourceOverrides map[string]appv1.ResourceOverride, app *appv1.Application, persistResourceHealth bool) (*appv1.HealthStatus, error) {
var savedErr error
var errCount uint
- appHealthStatus := health.HealthStatusHealthy
+ appHealth := app.Status.Health.DeepCopy()
+ appHealth.Status = health.HealthStatusHealthy
+
for i, res := range resources {
if res.Target != nil && hookutil.Skip(res.Target) {
continue
@@ -51,7 +52,7 @@ func setApplicationHealth(resources []managedResource, statuses []appv1.Resource
errCount++
savedErr = fmt.Errorf("failed to get resource health for %q with name %q in namespace %q: %w", res.Live.GetKind(), res.Live.GetName(), res.Live.GetNamespace(), err)
// also log so we don't lose the message
- log.WithFields(applog.GetAppLogFields(app)).Warn(savedErr)
+ log.WithField("application", app.QualifiedName()).Warn(savedErr)
}
}
@@ -76,8 +77,8 @@ func setApplicationHealth(resources []managedResource, statuses []appv1.Resource
continue
}
- if health.IsWorse(appHealthStatus, healthStatus.Status) {
- appHealthStatus = healthStatus.Status
+ if health.IsWorse(appHealth.Status, healthStatus.Status) {
+ appHealth.Status = healthStatus.Status
}
}
if persistResourceHealth {
@@ -88,5 +89,5 @@ func setApplicationHealth(resources []managedResource, statuses []appv1.Resource
if savedErr != nil && errCount > 1 {
savedErr = fmt.Errorf("see application-controller logs for %d other errors; most recent error was: %w", errCount-1, savedErr)
}
- return appHealthStatus, savedErr
+ return appHealth, savedErr
}
diff --git a/controller/health_test.go b/controller/health_test.go
index fff2adce73..03594df26b 100644
--- a/controller/health_test.go
+++ b/controller/health_test.go
@@ -16,15 +16,15 @@ import (
"k8s.io/apimachinery/pkg/runtime/schema"
"sigs.k8s.io/yaml"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application"
- appv1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- "github.com/argoproj/argo-cd/v3/util/lua"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application"
+ appv1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/util/lua"
)
var (
app = &appv1.Application{
Status: appv1.ApplicationStatus{
- Health: appv1.AppHealthStatus{
+ Health: appv1.HealthStatus{
LastTransitionTime: &metav1.Time{Time: time.Date(2020, time.January, 1, 12, 0, 0, 0, time.UTC)},
},
},
@@ -66,17 +66,23 @@ func TestSetApplicationHealth(t *testing.T) {
healthStatus, err := setApplicationHealth(resources, resourceStatuses, lua.ResourceHealthOverrides{}, app, true)
require.NoError(t, err)
- assert.Equal(t, health.HealthStatusDegraded, healthStatus)
+ assert.Equal(t, health.HealthStatusDegraded, healthStatus.Status)
assert.Equal(t, health.HealthStatusHealthy, resourceStatuses[0].Health.Status)
assert.Equal(t, health.HealthStatusDegraded, resourceStatuses[1].Health.Status)
- app.Status.Health.Status = healthStatus
+ // Health.LastTransitionTime is set only for app health and not at individual resource level
+ assert.NotNil(t, healthStatus.LastTransitionTime)
+ assert.Nil(t, resourceStatuses[0].Health.LastTransitionTime)
+ assert.Nil(t, resourceStatuses[1].Health.LastTransitionTime)
+ app.Status.Health = *healthStatus
// now mark the job as a hook and retry. it should ignore the hook and consider the app healthy
failedJob.SetAnnotations(map[string]string{synccommon.AnnotationKeyHook: "PreSync"})
healthStatus, err = setApplicationHealth(resources, resourceStatuses, nil, app, true)
require.NoError(t, err)
- assert.Equal(t, health.HealthStatusHealthy, healthStatus)
- app.Status.Health.Status = healthStatus
+ assert.Equal(t, health.HealthStatusHealthy, healthStatus.Status)
+ // timestamp should be the same in case health did not change
+ assert.Equal(t, app.Status.Health.LastTransitionTime, healthStatus.LastTransitionTime)
+ app.Status.Health = *healthStatus
// now we set the `argocd.argoproj.io/ignore-healthcheck: "true"` annotation on the job's target.
// The app is considered healthy
@@ -85,7 +91,8 @@ func TestSetApplicationHealth(t *testing.T) {
resources[1].Target = &failedJobIgnoreHealthcheck
healthStatus, err = setApplicationHealth(resources, resourceStatuses, nil, app, true)
require.NoError(t, err)
- assert.Equal(t, health.HealthStatusHealthy, healthStatus)
+ assert.Equal(t, health.HealthStatusHealthy, healthStatus.Status)
+ assert.Equal(t, app.Status.Health.LastTransitionTime, healthStatus.LastTransitionTime)
}
func TestSetApplicationHealth_ResourceHealthNotPersisted(t *testing.T) {
@@ -98,7 +105,7 @@ func TestSetApplicationHealth_ResourceHealthNotPersisted(t *testing.T) {
healthStatus, err := setApplicationHealth(resources, resourceStatuses, lua.ResourceHealthOverrides{}, app, false)
require.NoError(t, err)
- assert.Equal(t, health.HealthStatusDegraded, healthStatus)
+ assert.Equal(t, health.HealthStatusDegraded, healthStatus.Status)
assert.Nil(t, resourceStatuses[0].Health)
}
@@ -113,7 +120,8 @@ func TestSetApplicationHealth_MissingResource(t *testing.T) {
healthStatus, err := setApplicationHealth(resources, resourceStatuses, lua.ResourceHealthOverrides{}, app, true)
require.NoError(t, err)
- assert.Equal(t, health.HealthStatusMissing, healthStatus)
+ assert.Equal(t, health.HealthStatusMissing, healthStatus.Status)
+ assert.Equal(t, app.Status.Health.LastTransitionTime, healthStatus.LastTransitionTime)
}
func TestSetApplicationHealth_HealthImproves(t *testing.T) {
@@ -144,7 +152,8 @@ func TestSetApplicationHealth_HealthImproves(t *testing.T) {
t.Run(string(fmt.Sprintf("%s to %s", tc.oldStatus, tc.newStatus)), func(t *testing.T) {
healthStatus, err := setApplicationHealth(resources, resourceStatuses, overrides, app, true)
require.NoError(t, err)
- assert.Equal(t, tc.newStatus, healthStatus)
+ assert.Equal(t, tc.newStatus, healthStatus.Status)
+ assert.Equal(t, app.Status.Health.LastTransitionTime, healthStatus.LastTransitionTime)
})
}
}
@@ -160,7 +169,8 @@ func TestSetApplicationHealth_MissingResourceNoBuiltHealthCheck(t *testing.T) {
t.Run("NoOverride", func(t *testing.T) {
healthStatus, err := setApplicationHealth(resources, resourceStatuses, lua.ResourceHealthOverrides{}, app, true)
require.NoError(t, err)
- assert.Equal(t, health.HealthStatusHealthy, healthStatus)
+ assert.Equal(t, health.HealthStatusHealthy, healthStatus.Status)
+ assert.Equal(t, app.Status.Health.LastTransitionTime, healthStatus.LastTransitionTime)
assert.Equal(t, health.HealthStatusMissing, resourceStatuses[0].Health.Status)
})
@@ -171,7 +181,8 @@ func TestSetApplicationHealth_MissingResourceNoBuiltHealthCheck(t *testing.T) {
},
}, app, true)
require.NoError(t, err)
- assert.Equal(t, health.HealthStatusMissing, healthStatus)
+ assert.Equal(t, health.HealthStatusMissing, healthStatus.Status)
+ assert.Equal(t, app.Status.Health.LastTransitionTime, healthStatus.LastTransitionTime)
})
}
@@ -185,7 +196,7 @@ func newAppLiveObj(status health.HealthStatusCode) *unstructured.Unstructured {
Kind: application.ApplicationKind,
},
Status: appv1.ApplicationStatus{
- Health: appv1.AppHealthStatus{
+ Health: appv1.HealthStatus{
Status: status,
},
},
@@ -222,7 +233,7 @@ return hs`,
healthStatus, err := setApplicationHealth(resources, resourceStatuses, overrides, app, true)
require.NoError(t, err)
- assert.Equal(t, health.HealthStatusDegraded, healthStatus)
+ assert.Equal(t, health.HealthStatusDegraded, healthStatus.Status)
})
t.Run("ChildAppMissing", func(t *testing.T) {
@@ -234,6 +245,6 @@ return hs`,
healthStatus, err := setApplicationHealth(resources, resourceStatuses, overrides, app, true)
require.NoError(t, err)
- assert.Equal(t, health.HealthStatusHealthy, healthStatus)
+ assert.Equal(t, health.HealthStatusHealthy, healthStatus.Status)
})
}
diff --git a/controller/hook.go b/controller/hook.go
index 2bf30d1b7f..b0fd8ebb03 100644
--- a/controller/hook.go
+++ b/controller/hook.go
@@ -8,13 +8,13 @@ import (
"github.com/argoproj/gitops-engine/pkg/sync/hook"
"github.com/argoproj/gitops-engine/pkg/utils/kube"
log "github.com/sirupsen/logrus"
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+ v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/client-go/rest"
- "github.com/argoproj/argo-cd/v3/util/lua"
+ "github.com/argoproj/argo-cd/v2/util/lua"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
)
var (
@@ -76,7 +76,7 @@ func (ctrl *ApplicationController) executePostDeleteHooks(app *v1alpha1.Applicat
}
createdCnt := 0
for _, obj := range expectedHook {
- _, err = ctrl.kubectl.CreateResource(context.Background(), config, obj.GroupVersionKind(), obj.GetName(), obj.GetNamespace(), obj, metav1.CreateOptions{})
+ _, err = ctrl.kubectl.CreateResource(context.Background(), config, obj.GroupVersionKind(), obj.GetName(), obj.GetNamespace(), obj, v1.CreateOptions{})
if err != nil {
return false, err
}
@@ -159,7 +159,7 @@ func (ctrl *ApplicationController) cleanupPostDeleteHooks(liveObjs map[kube.Reso
continue
}
logCtx.Infof("Deleting post-delete hook %s/%s", obj.GetNamespace(), obj.GetName())
- err = ctrl.kubectl.DeleteResource(context.Background(), config, obj.GroupVersionKind(), obj.GetName(), obj.GetNamespace(), metav1.DeleteOptions{})
+ err = ctrl.kubectl.DeleteResource(context.Background(), config, obj.GroupVersionKind(), obj.GetName(), obj.GetNamespace(), v1.DeleteOptions{})
if err != nil {
return false, err
}
diff --git a/controller/hydrator/hydrator.go b/controller/hydrator/hydrator.go
index 023fb360f4..6c16d97dbe 100644
--- a/controller/hydrator/hydrator.go
+++ b/controller/hydrator/hydrator.go
@@ -10,11 +10,11 @@ import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
- commitclient "github.com/argoproj/argo-cd/v3/commitserver/apiclient"
- appv1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- "github.com/argoproj/argo-cd/v3/reposerver/apiclient"
- applog "github.com/argoproj/argo-cd/v3/util/app/log"
- utilio "github.com/argoproj/argo-cd/v3/util/io"
+ commitclient "github.com/argoproj/argo-cd/v2/commitserver/apiclient"
+ "github.com/argoproj/argo-cd/v2/controller/utils"
+ appv1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/reposerver/apiclient"
+ argoio "github.com/argoproj/argo-cd/v2/util/io"
)
// Dependencies is the interface for the dependencies of the Hydrator. It serves two purposes: 1) it prevents the
@@ -55,7 +55,7 @@ func (h *Hydrator) ProcessAppHydrateQueueItem(origApp *appv1.Application) {
return
}
- logCtx := log.WithFields(applog.GetAppLogFields(app))
+ logCtx := utils.GetAppLog(app)
logCtx.Debug("Processing app hydrate queue item")
@@ -130,7 +130,7 @@ func (h *Hydrator) ProcessHydrationQueueItem(hydrationKey HydrationQueueKey) (pr
// in case we did.
app.Status.SourceHydrator.CurrentOperation.DrySHA = drySHA
h.dependencies.PersistAppHydratorStatus(origApp, &app.Status.SourceHydrator)
- logCtx = logCtx.WithFields(applog.GetAppLogFields(app))
+ logCtx = logCtx.WithField("app", app.QualifiedName())
logCtx.Errorf("Failed to hydrate app: %v", err)
}
return
@@ -262,7 +262,7 @@ func (h *Hydrator) hydrate(logCtx *log.Entry, apps []*appv1.Application) (string
// TODO: enable signature verification
objs, resp, err := h.dependencies.GetRepoObjs(app, drySource, targetRevision, project)
if err != nil {
- return "", "", fmt.Errorf("failed to get repo objects for app %q: %w", app.QualifiedName(), err)
+ return "", "", fmt.Errorf("failed to get repo objects: %w", err)
}
// This should be the DRY SHA. We set it here so that after processing the first app, all apps are hydrated
@@ -272,11 +272,11 @@ func (h *Hydrator) hydrate(logCtx *log.Entry, apps []*appv1.Application) (string
// Set up a ManifestsRequest
manifestDetails := make([]*commitclient.HydratedManifestDetails, len(objs))
for i, obj := range objs {
- objJSON, err := json.Marshal(obj)
+ objJson, err := json.Marshal(obj)
if err != nil {
return "", "", fmt.Errorf("failed to marshal object: %w", err)
}
- manifestDetails[i] = &commitclient.HydratedManifestDetails{ManifestJSON: string(objJSON)}
+ manifestDetails[i] = &commitclient.HydratedManifestDetails{ManifestJSON: string(objJson)}
}
paths = append(paths, &commitclient.PathDetails{
@@ -312,7 +312,7 @@ func (h *Hydrator) hydrate(logCtx *log.Entry, apps []*appv1.Application) (string
SyncBranch: syncBranch,
TargetBranch: targetBranch,
DrySha: targetRevision,
- CommitMessage: "[Argo CD Bot] hydrate " + targetRevision,
+ CommitMessage: fmt.Sprintf("[Argo CD Bot] hydrate %s", targetRevision),
Paths: paths,
}
@@ -320,7 +320,7 @@ func (h *Hydrator) hydrate(logCtx *log.Entry, apps []*appv1.Application) (string
if err != nil {
return targetRevision, "", fmt.Errorf("failed to create commit service: %w", err)
}
- defer utilio.Close(closer)
+ defer argoio.Close(closer)
resp, err := commitService.CommitHydratedManifests(context.Background(), &manifestsRequest)
if err != nil {
return targetRevision, "", fmt.Errorf("failed to commit hydrated manifests: %w", err)
@@ -339,16 +339,15 @@ func appNeedsHydration(app *appv1.Application, statusHydrateTimeout time.Duratio
hydratedAt = &app.Status.SourceHydrator.CurrentOperation.StartedAt
}
- switch {
- case app.IsHydrateRequested():
+ if app.IsHydrateRequested() {
return true, "hydrate requested"
- case app.Status.SourceHydrator.CurrentOperation == nil:
+ } else if app.Status.SourceHydrator.CurrentOperation == nil {
return true, "no previous hydrate operation"
- case !app.Spec.SourceHydrator.DeepEquals(app.Status.SourceHydrator.CurrentOperation.SourceHydrator):
+ } else if !app.Spec.SourceHydrator.DeepEquals(app.Status.SourceHydrator.CurrentOperation.SourceHydrator) {
return true, "spec.sourceHydrator differs"
- case app.Status.SourceHydrator.CurrentOperation.Phase == appv1.HydrateOperationPhaseFailed && metav1.Now().Sub(app.Status.SourceHydrator.CurrentOperation.FinishedAt.Time) > 2*time.Minute:
+ } else if app.Status.SourceHydrator.CurrentOperation.Phase == appv1.HydrateOperationPhaseFailed && metav1.Now().Sub(app.Status.SourceHydrator.CurrentOperation.FinishedAt.Time) > 2*time.Minute {
return true, "previous hydrate operation failed more than 2 minutes ago"
- case hydratedAt == nil || hydratedAt.Add(statusHydrateTimeout).Before(time.Now().UTC()):
+ } else if hydratedAt == nil || hydratedAt.Add(statusHydrateTimeout).Before(time.Now().UTC()) {
return true, "hydration expired"
}
diff --git a/controller/hydrator/hydrator_test.go b/controller/hydrator/hydrator_test.go
index e0b7cfee79..c4e62931a5 100644
--- a/controller/hydrator/hydrator_test.go
+++ b/controller/hydrator/hydrator_test.go
@@ -7,7 +7,7 @@ import (
"github.com/stretchr/testify/assert"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
)
func Test_appNeedsHydration(t *testing.T) {
diff --git a/controller/hydrator_dependencies.go b/controller/hydrator_dependencies.go
index e846499248..a65fb7d2c3 100644
--- a/controller/hydrator_dependencies.go
+++ b/controller/hydrator_dependencies.go
@@ -4,10 +4,10 @@ import (
"context"
"fmt"
- "github.com/argoproj/argo-cd/v3/controller/hydrator"
- appv1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- "github.com/argoproj/argo-cd/v3/reposerver/apiclient"
- argoutil "github.com/argoproj/argo-cd/v3/util/argo"
+ "github.com/argoproj/argo-cd/v2/controller/hydrator"
+ appv1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/reposerver/apiclient"
+ argoutil "github.com/argoproj/argo-cd/v2/util/argo"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
diff --git a/controller/metrics/clustercollector.go b/controller/metrics/clustercollector.go
index 1881ae6efe..edbe8c2581 100644
--- a/controller/metrics/clustercollector.go
+++ b/controller/metrics/clustercollector.go
@@ -6,27 +6,21 @@ import (
"time"
"github.com/argoproj/gitops-engine/pkg/cache"
- "github.com/prometheus/client_golang/prometheus"
- log "github.com/sirupsen/logrus"
- argoappv1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- metricsutil "github.com/argoproj/argo-cd/v3/util/metrics"
+ "github.com/prometheus/client_golang/prometheus"
)
const (
metricsCollectionInterval = 30 * time.Second
- metricsCollectionTimeout = 10 * time.Second
)
var (
descClusterDefaultLabels = []string{"server"}
- descClusterLabels *prometheus.Desc
-
descClusterInfo = prometheus.NewDesc(
"argocd_cluster_info",
"Information about cluster.",
- append(descClusterDefaultLabels, "k8s_version", "name"),
+ append(descClusterDefaultLabels, "k8s_version"),
nil,
)
descClusterCacheResources = prometheus.NewDesc(
@@ -59,101 +53,30 @@ type HasClustersInfo interface {
GetClustersInfo() []cache.ClusterInfo
}
-type ClusterLister func(ctx context.Context) (*argoappv1.ClusterList, error)
-
type clusterCollector struct {
- infoSource HasClustersInfo
- lock sync.RWMutex
- clusterLabels []string
- clusterLister ClusterLister
-
- latestInfo []*clusterData
+ infoSource HasClustersInfo
+ info []cache.ClusterInfo
+ lock sync.Mutex
}
-type clusterData struct {
- info *cache.ClusterInfo
- cluster *argoappv1.Cluster
-}
-
-func NewClusterCollector(ctx context.Context, source HasClustersInfo, clusterLister ClusterLister, clusterLabels []string) prometheus.Collector {
- if len(clusterLabels) > 0 {
- normalizedClusterLabels := metricsutil.NormalizeLabels("label", clusterLabels)
- descClusterLabels = prometheus.NewDesc(
- "argocd_cluster_labels",
- "Argo Cluster labels converted to Prometheus labels",
- append(append(descClusterDefaultLabels, "name"), normalizedClusterLabels...),
- nil,
- )
- }
-
- collector := &clusterCollector{
- infoSource: source,
- clusterLabels: clusterLabels,
- clusterLister: clusterLister,
- lock: sync.RWMutex{},
- }
-
- collector.setClusterData()
- go collector.run(ctx)
-
- return collector
-}
-
-func (c *clusterCollector) run(ctx context.Context) {
- //nolint:staticcheck // FIXME: complains about SA1015
+func (c *clusterCollector) Run(ctx context.Context) {
+ // FIXME: complains about SA1015
+ // nolint:staticcheck
tick := time.Tick(metricsCollectionInterval)
for {
select {
case <-ctx.Done():
+ break
case <-tick:
- c.setClusterData()
+ info := c.infoSource.GetClustersInfo()
+
+ c.lock.Lock()
+ c.info = info
+ c.lock.Unlock()
}
}
}
-func (c *clusterCollector) setClusterData() {
- if clusterData, err := c.getClusterData(); err == nil {
- c.lock.Lock()
- c.latestInfo = clusterData
- c.lock.Unlock()
- } else {
- log.Warnf("error collecting cluster metrics: %v", err)
- }
-}
-
-func (c *clusterCollector) getClusterData() ([]*clusterData, error) {
- clusterDatas := []*clusterData{}
- clusterInfos := c.infoSource.GetClustersInfo()
-
- ctx, cancel := context.WithTimeout(context.Background(), metricsCollectionTimeout)
- defer cancel()
- clusters, err := c.clusterLister(ctx)
- if err != nil {
- return nil, err
- }
-
- clusterMap := map[string]*argoappv1.Cluster{}
- for i, cluster := range clusters.Items {
- clusterMap[cluster.Server] = &clusters.Items[i]
- }
-
- // Base the cluster data on the ClusterInfo because it only contains the
- // clusters managed by this controller instance
- for i, info := range clusterInfos {
- cluster, ok := clusterMap[info.Server]
- if !ok {
- // This should not happen, but we cannot emit incomplete metrics, so we skip this cluster
- log.WithField("server", info.Server).Warnf("could find cluster for metrics collection")
- continue
- }
- clusterDatas = append(clusterDatas, &clusterData{
- info: &clusterInfos[i],
- cluster: cluster,
- })
- }
- return clusterDatas, nil
-}
-
// Describe implements the prometheus.Collector interface
func (c *clusterCollector) Describe(ch chan<- *prometheus.Desc) {
ch <- descClusterInfo
@@ -161,41 +84,20 @@ func (c *clusterCollector) Describe(ch chan<- *prometheus.Desc) {
ch <- descClusterAPIs
ch <- descClusterCacheAgeSeconds
ch <- descClusterConnectionStatus
- if len(c.clusterLabels) > 0 {
- ch <- descClusterLabels
- }
}
func (c *clusterCollector) Collect(ch chan<- prometheus.Metric) {
- c.lock.RLock()
- latestInfo := c.latestInfo
- c.lock.RUnlock()
-
now := time.Now()
- for _, clusterData := range latestInfo {
- info := clusterData.info
- name := clusterData.cluster.Name
- labels := clusterData.cluster.Labels
-
- defaultValues := []string{info.Server}
- ch <- prometheus.MustNewConstMetric(descClusterInfo, prometheus.GaugeValue, 1, append(defaultValues, info.K8SVersion, name)...)
- ch <- prometheus.MustNewConstMetric(descClusterCacheResources, prometheus.GaugeValue, float64(info.ResourcesCount), defaultValues...)
- ch <- prometheus.MustNewConstMetric(descClusterAPIs, prometheus.GaugeValue, float64(info.APIsCount), defaultValues...)
+ for _, c := range c.info {
+ defaultValues := []string{c.Server}
+ ch <- prometheus.MustNewConstMetric(descClusterInfo, prometheus.GaugeValue, 1, append(defaultValues, c.K8SVersion)...)
+ ch <- prometheus.MustNewConstMetric(descClusterCacheResources, prometheus.GaugeValue, float64(c.ResourcesCount), defaultValues...)
+ ch <- prometheus.MustNewConstMetric(descClusterAPIs, prometheus.GaugeValue, float64(c.APIsCount), defaultValues...)
cacheAgeSeconds := -1
- if info.LastCacheSyncTime != nil {
- cacheAgeSeconds = int(now.Sub(*info.LastCacheSyncTime).Seconds())
+ if c.LastCacheSyncTime != nil {
+ cacheAgeSeconds = int(now.Sub(*c.LastCacheSyncTime).Seconds())
}
ch <- prometheus.MustNewConstMetric(descClusterCacheAgeSeconds, prometheus.GaugeValue, float64(cacheAgeSeconds), defaultValues...)
- ch <- prometheus.MustNewConstMetric(descClusterConnectionStatus, prometheus.GaugeValue, boolFloat64(info.SyncError == nil), append(defaultValues, info.K8SVersion)...)
-
- if len(c.clusterLabels) > 0 && labels != nil {
- labelValues := []string{}
- labelValues = append(labelValues, info.Server, name)
- for _, desiredLabel := range c.clusterLabels {
- value := labels[desiredLabel]
- labelValues = append(labelValues, value)
- }
- ch <- prometheus.MustNewConstMetric(descClusterLabels, prometheus.GaugeValue, 1, labelValues...)
- }
+ ch <- prometheus.MustNewConstMetric(descClusterConnectionStatus, prometheus.GaugeValue, boolFloat64(c.SyncError == nil), append(defaultValues, c.K8SVersion)...)
}
}
diff --git a/controller/metrics/clustercollector_test.go b/controller/metrics/clustercollector_test.go
index 3f1881447b..cbe124ca29 100644
--- a/controller/metrics/clustercollector_test.go
+++ b/controller/metrics/clustercollector_test.go
@@ -5,36 +5,21 @@ import (
"testing"
gitopsCache "github.com/argoproj/gitops-engine/pkg/cache"
- "github.com/stretchr/testify/mock"
-
- dbmocks "github.com/argoproj/argo-cd/v3/util/db/mocks"
-
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
)
func TestMetricClusterConnectivity(t *testing.T) {
- db := dbmocks.ArgoDB{}
- cluster1 := v1alpha1.Cluster{Name: "cluster1", Server: "server1", Labels: map[string]string{"env": "dev", "team": "team1"}}
- cluster2 := v1alpha1.Cluster{Name: "cluster2", Server: "server2", Labels: map[string]string{"env": "staging", "team": "team2"}}
- cluster3 := v1alpha1.Cluster{Name: "cluster3", Server: "server3", Labels: map[string]string{"env": "production", "team": "team3"}}
- clusterList := &v1alpha1.ClusterList{Items: []v1alpha1.Cluster{cluster1, cluster2, cluster3}}
- db.On("ListClusters", mock.Anything).Return(clusterList, nil)
-
type testCases struct {
testCombination
- skip bool
- description string
- metricLabels []string
- clusterLabels []string
- clustersInfo []gitopsCache.ClusterInfo
+ skip bool
+ description string
+ metricLabels []string
+ clustersInfo []gitopsCache.ClusterInfo
}
-
cases := []testCases{
{
- description: "metric will have value 1 if connected with the cluster",
- skip: false,
- metricLabels: []string{"non-existing"},
- clusterLabels: []string{"env"},
+ description: "metric will have value 1 if connected with the cluster",
+ skip: false,
+ metricLabels: []string{"non-existing"},
testCombination: testCombination{
applications: []string{fakeApp},
responseContains: `
@@ -51,10 +36,9 @@ argocd_cluster_connection_status{k8s_version="1.21",server="server1"} 1
},
},
{
- description: "metric will have value 0 if not connected with the cluster",
- skip: false,
- metricLabels: []string{"non-existing"},
- clusterLabels: []string{"env"},
+ description: "metric will have value 0 if not connected with the cluster",
+ skip: false,
+ metricLabels: []string{"non-existing"},
testCombination: testCombination{
applications: []string{fakeApp},
responseContains: `
@@ -71,10 +55,9 @@ argocd_cluster_connection_status{k8s_version="1.21",server="server1"} 0
},
},
{
- description: "will have one metric per cluster",
- skip: false,
- metricLabels: []string{"non-existing"},
- clusterLabels: []string{"env", "team"},
+ description: "will have one metric per cluster",
+ skip: false,
+ metricLabels: []string{"non-existing"},
testCombination: testCombination{
applications: []string{fakeApp},
responseContains: `
@@ -82,16 +65,6 @@ argocd_cluster_connection_status{k8s_version="1.21",server="server1"} 0
argocd_cluster_connection_status{k8s_version="1.21",server="server1"} 1
argocd_cluster_connection_status{k8s_version="1.21",server="server2"} 1
argocd_cluster_connection_status{k8s_version="1.21",server="server3"} 1
-
-# TYPE argocd_cluster_info gauge
-argocd_cluster_info{k8s_version="1.21",name="cluster1",server="server1"} 1
-argocd_cluster_info{k8s_version="1.21",name="cluster2",server="server2"} 1
-argocd_cluster_info{k8s_version="1.21",name="cluster3",server="server3"} 1
-
-# TYPE argocd_cluster_labels gauge
-argocd_cluster_labels{label_env="dev",label_team="team1",name="cluster1",server="server1"} 1
-argocd_cluster_labels{label_env="staging",label_team="team2",name="cluster2",server="server2"} 1
-argocd_cluster_labels{label_env="production",label_team="team3",name="cluster3",server="server3"} 1
`,
},
clustersInfo: []gitopsCache.ClusterInfo{
@@ -122,9 +95,7 @@ argocd_cluster_labels{label_env="production",label_team="team3",name="cluster3",
FakeAppYAMLs: c.applications,
ExpectedResponse: c.responseContains,
AppLabels: c.metricLabels,
- ClusterLabels: c.clusterLabels,
ClustersInfo: c.clustersInfo,
- ClusterLister: db.ListClusters,
}
runTest(t, cfg)
}
diff --git a/controller/metrics/metrics.go b/controller/metrics/metrics.go
index 47a6396182..70339499e0 100644
--- a/controller/metrics/metrics.go
+++ b/controller/metrics/metrics.go
@@ -16,17 +16,16 @@ import (
"github.com/robfig/cron/v3"
log "github.com/sirupsen/logrus"
"k8s.io/apimachinery/pkg/labels"
- ctrlmetrics "sigs.k8s.io/controller-runtime/pkg/metrics"
- "github.com/argoproj/argo-cd/v3/common"
- argoappv1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- applister "github.com/argoproj/argo-cd/v3/pkg/client/listers/application/v1alpha1"
- "github.com/argoproj/argo-cd/v3/util/db"
- "github.com/argoproj/argo-cd/v3/util/git"
- "github.com/argoproj/argo-cd/v3/util/healthz"
- metricsutil "github.com/argoproj/argo-cd/v3/util/metrics"
- "github.com/argoproj/argo-cd/v3/util/metrics/kubectl"
- "github.com/argoproj/argo-cd/v3/util/profile"
+ "github.com/argoproj/argo-cd/v2/common"
+ argoappv1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+ applister "github.com/argoproj/argo-cd/v2/pkg/client/listers/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/util/git"
+ "github.com/argoproj/argo-cd/v2/util/healthz"
+ metricsutil "github.com/argoproj/argo-cd/v2/util/metrics"
+ "github.com/argoproj/argo-cd/v2/util/profile"
+
+ ctrl_metrics "sigs.k8s.io/controller-runtime/pkg/metrics"
)
type MetricsServer struct {
@@ -50,6 +49,8 @@ type MetricsServer struct {
const (
// MetricsPath is the endpoint to collect application metrics
MetricsPath = "/metrics"
+ // EnvVarLegacyControllerMetrics is a env var to re-enable deprecated prometheus metrics
+ EnvVarLegacyControllerMetrics = "ARGOCD_LEGACY_CONTROLLER_METRICS"
)
// Follow Prometheus naming practices
@@ -67,12 +68,34 @@ var (
nil,
)
+ // Deprecated
+ descAppCreated = prometheus.NewDesc(
+ "argocd_app_created_time",
+ "Creation time in unix timestamp for an application.",
+ descAppDefaultLabels,
+ nil,
+ )
+ // Deprecated: superseded by sync_status label in argocd_app_info
+ descAppSyncStatusCode = prometheus.NewDesc(
+ "argocd_app_sync_status",
+ "The application current sync status.",
+ append(descAppDefaultLabels, "sync_status"),
+ nil,
+ )
+ // Deprecated: superseded by health_status label in argocd_app_info
+ descAppHealthStatus = prometheus.NewDesc(
+ "argocd_app_health_status",
+ "The application current health status.",
+ append(descAppDefaultLabels, "health_status"),
+ nil,
+ )
+
syncCounter = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "argocd_app_sync_total",
Help: "Number of application syncs.",
},
- append(descAppDefaultLabels, "dest_server", "phase", "dry_run"),
+ append(descAppDefaultLabels, "dest_server", "phase"),
)
k8sRequestCounter = prometheus.NewCounterVec(
@@ -80,7 +103,7 @@ var (
Name: "argocd_app_k8s_request_total",
Help: "Number of kubernetes requests executed during application reconciliation.",
},
- append(descAppDefaultLabels, "server", "response_code", "verb", "resource_kind", "resource_namespace", "dry_run"),
+ append(descAppDefaultLabels, "server", "response_code", "verb", "resource_kind", "resource_namespace"),
)
kubectlExecCounter = prometheus.NewCounterVec(prometheus.CounterOpts{
@@ -149,7 +172,7 @@ var (
)
// NewMetricsServer returns a new prometheus server which collects application metrics
-func NewMetricsServer(addr string, appLister applister.ApplicationLister, appFilter func(obj any) bool, healthCheck func(r *http.Request) error, appLabels []string, appConditions []string) (*MetricsServer, error) {
+func NewMetricsServer(addr string, appLister applister.ApplicationLister, appFilter func(obj interface{}) bool, healthCheck func(r *http.Request) error, appLabels []string, appConditions []string) (*MetricsServer, error) {
hostname, err := os.Hostname()
if err != nil {
return nil, err
@@ -181,7 +204,7 @@ func NewMetricsServer(addr string, appLister applister.ApplicationLister, appFil
// contains app controller specific metrics
registry,
// contains workqueue metrics, process and golang metrics
- ctrlmetrics.Registry,
+ ctrl_metrics.Registry,
}, promhttp.HandlerOpts{}))
profile.RegisterProfiler(mux)
healthz.ServeHealthCheck(mux, healthCheck)
@@ -198,11 +221,7 @@ func NewMetricsServer(addr string, appLister applister.ApplicationLister, appFil
registry.MustRegister(resourceEventsProcessingHistogram)
registry.MustRegister(resourceEventsNumberGauge)
- kubectlMetricsServer := kubectl.NewKubectlMetrics()
- kubectlMetricsServer.RegisterWithClientGo()
- kubectl.RegisterWithPrometheus(registry)
-
- metricsServer := &MetricsServer{
+ return &MetricsServer{
registry: registry,
Server: &http.Server{
Addr: addr,
@@ -224,13 +243,12 @@ func NewMetricsServer(addr string, appLister applister.ApplicationLister, appFil
// Currently clearing the metrics cache is logging and deleting from the map
// so there is no possibility of panic, but we will add a chain to keep robfig/cron v1 behavior.
cron: cron.New(cron.WithChain(cron.Recover(cron.PrintfLogger(log.StandardLogger())))),
- }
-
- return metricsServer, nil
+ }, nil
}
-func (m *MetricsServer) RegisterClustersInfoSource(ctx context.Context, source HasClustersInfo, db db.ArgoDB, clusterLabels []string) {
- collector := NewClusterCollector(ctx, source, db.ListClusters, clusterLabels)
+func (m *MetricsServer) RegisterClustersInfoSource(ctx context.Context, source HasClustersInfo) {
+ collector := &clusterCollector{infoSource: source}
+ go collector.Run(ctx)
m.registry.MustRegister(collector)
}
@@ -239,8 +257,7 @@ func (m *MetricsServer) IncSync(app *argoappv1.Application, state *argoappv1.Ope
if !state.Phase.Completed() {
return
}
- isDryRun := app.Operation != nil && app.Operation.DryRun()
- m.syncCounter.WithLabelValues(app.Namespace, app.Name, app.Spec.GetProject(), app.Spec.Destination.Server, string(state.Phase), strconv.FormatBool(isDryRun)).Inc()
+ m.syncCounter.WithLabelValues(app.Namespace, app.Name, app.Spec.GetProject(), app.Spec.Destination.Server, string(state.Phase)).Inc()
}
func (m *MetricsServer) IncKubectlExec(command string) {
@@ -267,16 +284,14 @@ func (m *MetricsServer) IncClusterEventsCount(server, group, kind string) {
// IncKubernetesRequest increments the kubernetes requests counter for an application
func (m *MetricsServer) IncKubernetesRequest(app *argoappv1.Application, server, statusCode, verb, resourceKind, resourceNamespace string) {
var namespace, name, project string
- isDryRun := false
if app != nil {
namespace = app.Namespace
name = app.Name
project = app.Spec.GetProject()
- isDryRun = app.Operation != nil && app.Operation.DryRun()
}
m.k8sRequestCounter.WithLabelValues(
namespace, name, project, server, statusCode,
- verb, resourceKind, resourceNamespace, strconv.FormatBool(isDryRun),
+ verb, resourceKind, resourceNamespace,
).Inc()
}
@@ -308,7 +323,7 @@ func (m *MetricsServer) HasExpiration() bool {
// SetExpiration reset Prometheus metrics based on time duration interval
func (m *MetricsServer) SetExpiration(cacheExpiration time.Duration) error {
if m.HasExpiration() {
- return errors.New("expiration is already set")
+ return errors.New("Expiration is already set")
}
_, err := m.cron.AddFunc(fmt.Sprintf("@every %s", cacheExpiration), func() {
@@ -324,7 +339,6 @@ func (m *MetricsServer) SetExpiration(cacheExpiration time.Duration) error {
m.redisRequestHistogram.Reset()
m.resourceEventsProcessingHistogram.Reset()
m.resourceEventsNumberGauge.Reset()
- kubectl.ResetAll()
})
if err != nil {
return err
@@ -336,13 +350,13 @@ func (m *MetricsServer) SetExpiration(cacheExpiration time.Duration) error {
type appCollector struct {
store applister.ApplicationLister
- appFilter func(obj any) bool
+ appFilter func(obj interface{}) bool
appLabels []string
appConditions []string
}
// NewAppCollector returns a prometheus collector for application metrics
-func NewAppCollector(appLister applister.ApplicationLister, appFilter func(obj any) bool, appLabels []string, appConditions []string) prometheus.Collector {
+func NewAppCollector(appLister applister.ApplicationLister, appFilter func(obj interface{}) bool, appLabels []string, appConditions []string) prometheus.Collector {
return &appCollector{
store: appLister,
appFilter: appFilter,
@@ -352,7 +366,7 @@ func NewAppCollector(appLister applister.ApplicationLister, appFilter func(obj a
}
// NewAppRegistry creates a new prometheus registry that collects applications
-func NewAppRegistry(appLister applister.ApplicationLister, appFilter func(obj any) bool, appLabels []string, appConditions []string) *prometheus.Registry {
+func NewAppRegistry(appLister applister.ApplicationLister, appFilter func(obj interface{}) bool, appLabels []string, appConditions []string) *prometheus.Registry {
registry := prometheus.NewRegistry()
registry.MustRegister(NewAppCollector(appLister, appFilter, appLabels, appConditions))
return registry
@@ -367,6 +381,8 @@ func (c *appCollector) Describe(ch chan<- *prometheus.Desc) {
ch <- descAppConditions
}
ch <- descAppInfo
+ ch <- descAppSyncStatusCode
+ ch <- descAppHealthStatus
}
// Collect implements the prometheus.Collector interface
@@ -415,7 +431,7 @@ func (c *appCollector) collectApps(ch chan<- prometheus.Metric, app *argoappv1.A
healthStatus = health.HealthStatusUnknown
}
- autoSyncEnabled := app.Spec.SyncPolicy != nil && app.Spec.SyncPolicy.IsAutomatedSyncEnabled()
+ autoSyncEnabled := app.Spec.SyncPolicy != nil && app.Spec.SyncPolicy.Automated != nil
addGauge(descAppInfo, 1, strconv.FormatBool(autoSyncEnabled), git.NormalizeGitURL(app.Spec.GetSource().RepoURL), app.Spec.Destination.Server, app.Spec.Destination.Namespace, string(syncStatus), string(healthStatus), operation)
@@ -440,4 +456,21 @@ func (c *appCollector) collectApps(ch chan<- prometheus.Metric, app *argoappv1.A
addGauge(descAppConditions, float64(count), conditionType)
}
}
+
+ // Deprecated controller metrics
+ if os.Getenv(EnvVarLegacyControllerMetrics) == "true" {
+ addGauge(descAppCreated, float64(app.CreationTimestamp.Unix()))
+
+ addGauge(descAppSyncStatusCode, boolFloat64(syncStatus == argoappv1.SyncStatusCodeSynced), string(argoappv1.SyncStatusCodeSynced))
+ addGauge(descAppSyncStatusCode, boolFloat64(syncStatus == argoappv1.SyncStatusCodeOutOfSync), string(argoappv1.SyncStatusCodeOutOfSync))
+ addGauge(descAppSyncStatusCode, boolFloat64(syncStatus == argoappv1.SyncStatusCodeUnknown || syncStatus == ""), string(argoappv1.SyncStatusCodeUnknown))
+
+ healthStatus := app.Status.Health.Status
+ addGauge(descAppHealthStatus, boolFloat64(healthStatus == health.HealthStatusUnknown || healthStatus == ""), string(health.HealthStatusUnknown))
+ addGauge(descAppHealthStatus, boolFloat64(healthStatus == health.HealthStatusProgressing), string(health.HealthStatusProgressing))
+ addGauge(descAppHealthStatus, boolFloat64(healthStatus == health.HealthStatusSuspended), string(health.HealthStatusSuspended))
+ addGauge(descAppHealthStatus, boolFloat64(healthStatus == health.HealthStatusHealthy), string(health.HealthStatusHealthy))
+ addGauge(descAppHealthStatus, boolFloat64(healthStatus == health.HealthStatusDegraded), string(health.HealthStatusDegraded))
+ addGauge(descAppHealthStatus, boolFloat64(healthStatus == health.HealthStatusMissing), string(health.HealthStatusMissing))
+ }
}
diff --git a/controller/metrics/metrics_test.go b/controller/metrics/metrics_test.go
index 7b66feb24f..383cb0c0c3 100644
--- a/controller/metrics/metrics_test.go
+++ b/controller/metrics/metrics_test.go
@@ -19,10 +19,10 @@ import (
"k8s.io/client-go/util/workqueue"
"sigs.k8s.io/yaml"
- argoappv1 "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- appclientset "github.com/argoproj/argo-cd/v3/pkg/client/clientset/versioned/fake"
- appinformer "github.com/argoproj/argo-cd/v3/pkg/client/informers/externalversions"
- applister "github.com/argoproj/argo-cd/v3/pkg/client/listers/application/v1alpha1"
+ argoappv1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+ appclientset "github.com/argoproj/argo-cd/v2/pkg/client/clientset/versioned/fake"
+ appinformer "github.com/argoproj/argo-cd/v2/pkg/client/informers/externalversions"
+ applister "github.com/argoproj/argo-cd/v2/pkg/client/listers/application/v1alpha1"
"sigs.k8s.io/controller-runtime/pkg/controller"
)
@@ -81,7 +81,6 @@ status:
status: Healthy
operation:
sync:
- dryRun: true
revision: 041eab7439ece92c99b043f0e171788185b8fc1d
syncStrategy:
hook: {}
@@ -172,11 +171,11 @@ status:
status: Healthy
`
-var noOpHealthCheck = func(_ *http.Request) error {
+var noOpHealthCheck = func(r *http.Request) error {
return nil
}
-var appFilter = func(_ any) bool {
+var appFilter = func(obj interface{}) bool {
return true
}
@@ -204,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(_ *metav1.ListOptions) {}))
+ factory := appinformer.NewSharedInformerFactoryWithOptions(appClientset, 0, appinformer.WithNamespace("argocd"), appinformer.WithTweakListOptions(func(options *metav1.ListOptions) {}))
appInformer := factory.Argoproj().V1alpha1().Applications().Informer()
go appInformer.Run(ctx.Done())
if !cache.WaitForCacheSync(ctx.Done(), appInformer.HasSynced) {
@@ -231,9 +230,7 @@ type TestMetricServerConfig struct {
ExpectedResponse string
AppLabels []string
AppConditions []string
- ClusterLabels []string
ClustersInfo []gitopsCache.ClusterInfo
- ClusterLister ClusterLister
}
func testMetricServer(t *testing.T, fakeAppYAMLs []string, expectedResponse string, appLabels []string, appConditions []string) {
@@ -243,7 +240,6 @@ func testMetricServer(t *testing.T, fakeAppYAMLs []string, expectedResponse stri
ExpectedResponse: expectedResponse,
AppLabels: appLabels,
AppConditions: appConditions,
- ClusterLabels: []string{},
ClustersInfo: []gitopsCache.ClusterInfo{},
}
runTest(t, cfg)
@@ -258,7 +254,10 @@ func runTest(t *testing.T, cfg TestMetricServerConfig) {
if len(cfg.ClustersInfo) > 0 {
ci := &fakeClusterInfo{clustersInfo: cfg.ClustersInfo}
- collector := NewClusterCollector(t.Context(), ci, cfg.ClusterLister, cfg.ClusterLabels)
+ collector := &clusterCollector{
+ infoSource: ci,
+ info: ci.GetClustersInfo(),
+ }
metricsServ.registry.MustRegister(collector)
}
@@ -400,6 +399,30 @@ argocd_app_condition{condition="ExcludedResourceWarning",name="my-app-4",namespa
}
}
+func TestLegacyMetrics(t *testing.T) {
+ t.Setenv(EnvVarLegacyControllerMetrics, "true")
+
+ expectedResponse := `
+# HELP argocd_app_created_time Creation time in unix timestamp for an application.
+# TYPE argocd_app_created_time gauge
+argocd_app_created_time{name="my-app",namespace="argocd",project="important-project"} -6.21355968e+10
+# HELP argocd_app_health_status The application current health status.
+# TYPE argocd_app_health_status gauge
+argocd_app_health_status{health_status="Degraded",name="my-app",namespace="argocd",project="important-project"} 0
+argocd_app_health_status{health_status="Healthy",name="my-app",namespace="argocd",project="important-project"} 1
+argocd_app_health_status{health_status="Missing",name="my-app",namespace="argocd",project="important-project"} 0
+argocd_app_health_status{health_status="Progressing",name="my-app",namespace="argocd",project="important-project"} 0
+argocd_app_health_status{health_status="Suspended",name="my-app",namespace="argocd",project="important-project"} 0
+argocd_app_health_status{health_status="Unknown",name="my-app",namespace="argocd",project="important-project"} 0
+# HELP argocd_app_sync_status The application current sync status.
+# TYPE argocd_app_sync_status gauge
+argocd_app_sync_status{name="my-app",namespace="argocd",project="important-project",sync_status="OutOfSync"} 0
+argocd_app_sync_status{name="my-app",namespace="argocd",project="important-project",sync_status="Synced"} 1
+argocd_app_sync_status{name="my-app",namespace="argocd",project="important-project",sync_status="Unknown"} 0
+`
+ testApp(t, []string{fakeApp}, expectedResponse)
+}
+
func TestMetricsSyncCounter(t *testing.T) {
cancel, appLister := newFakeLister()
defer cancel()
@@ -409,9 +432,9 @@ func TestMetricsSyncCounter(t *testing.T) {
appSyncTotal := `
# HELP argocd_app_sync_total Number of application syncs.
# TYPE argocd_app_sync_total counter
-argocd_app_sync_total{dest_server="https://localhost:6443",dry_run="false",name="my-app",namespace="argocd",phase="Error",project="important-project"} 1
-argocd_app_sync_total{dest_server="https://localhost:6443",dry_run="false",name="my-app",namespace="argocd",phase="Failed",project="important-project"} 1
-argocd_app_sync_total{dest_server="https://localhost:6443",dry_run="false",name="my-app",namespace="argocd",phase="Succeeded",project="important-project"} 2
+argocd_app_sync_total{dest_server="https://localhost:6443",name="my-app",namespace="argocd",phase="Error",project="important-project"} 1
+argocd_app_sync_total{dest_server="https://localhost:6443",name="my-app",namespace="argocd",phase="Failed",project="important-project"} 1
+argocd_app_sync_total{dest_server="https://localhost:6443",name="my-app",namespace="argocd",phase="Succeeded",project="important-project"} 2
`
fakeApp := newFakeApp(fakeApp)
@@ -520,9 +543,9 @@ func TestMetricsReset(t *testing.T) {
appSyncTotal := `
# HELP argocd_app_sync_total Number of application syncs.
# TYPE argocd_app_sync_total counter
-argocd_app_sync_total{dest_server="https://localhost:6443",dry_run="false",name="my-app",namespace="argocd",phase="Error",project="important-project"} 1
-argocd_app_sync_total{dest_server="https://localhost:6443",dry_run="false",name="my-app",namespace="argocd",phase="Failed",project="important-project"} 1
-argocd_app_sync_total{dest_server="https://localhost:6443",dry_run="false",name="my-app",namespace="argocd",phase="Succeeded",project="important-project"} 2
+argocd_app_sync_total{dest_server="https://localhost:6443",name="my-app",namespace="argocd",phase="Error",project="important-project"} 1
+argocd_app_sync_total{dest_server="https://localhost:6443",name="my-app",namespace="argocd",phase="Failed",project="important-project"} 1
+argocd_app_sync_total{dest_server="https://localhost:6443",name="my-app",namespace="argocd",phase="Succeeded",project="important-project"} 2
`
req, err := http.NewRequest(http.MethodGet, "/metrics", nil)
diff --git a/controller/metrics/transportwrapper.go b/controller/metrics/transportwrapper.go
index 01371c7710..637619bcd2 100644
--- a/controller/metrics/transportwrapper.go
+++ b/controller/metrics/transportwrapper.go
@@ -3,10 +3,10 @@ package metrics
import (
"strconv"
- "github.com/argoproj/pkg/v2/kubeclientmetrics"
+ "github.com/argoproj/pkg/kubeclientmetrics"
"k8s.io/client-go/rest"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
)
// AddMetricsTransportWrapper adds a transport wrapper which increments 'argocd_app_k8s_request_total' counter on each kubernetes request
diff --git a/controller/sharding/cache.go b/controller/sharding/cache.go
index 346145543a..4a750e3545 100644
--- a/controller/sharding/cache.go
+++ b/controller/sharding/cache.go
@@ -5,8 +5,8 @@ import (
log "github.com/sirupsen/logrus"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- "github.com/argoproj/argo-cd/v3/util/db"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/util/db"
)
type ClusterShardingCache interface {
@@ -20,7 +20,6 @@ type ClusterShardingCache interface {
IsManagedCluster(c *v1alpha1.Cluster) bool
GetDistribution() map[string]int
GetAppDistribution() map[string]int
- UpdateShard(shard int) bool
}
type ClusterSharding struct {
@@ -54,20 +53,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 (sharding *ClusterSharding) IsManagedCluster(c *v1alpha1.Cluster) bool {
- sharding.lock.RLock()
- defer sharding.lock.RUnlock()
+func (s *ClusterSharding) IsManagedCluster(c *v1alpha1.Cluster) bool {
+ s.lock.RLock()
+ defer s.lock.RUnlock()
if c == nil { // nil cluster (in-cluster) is always managed by current clusterShard
return true
}
clusterShard := 0
- if shard, ok := sharding.Shards[c.Server]; ok {
+ if shard, ok := s.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, sharding.Shard)
- return clusterShard == sharding.Shard
+ log.Debugf("Checking if cluster %s with clusterShard %d should be processed by shard %d", c.Server, clusterShard, s.Shard)
+ return clusterShard == s.Shard
}
func (sharding *ClusterSharding) Init(clusters *v1alpha1.ClusterList, apps *v1alpha1.ApplicationList) {
@@ -155,12 +154,11 @@ func (sharding *ClusterSharding) updateDistribution() {
}
existingShard, ok := sharding.Shards[k]
- switch {
- case ok && existingShard != shard:
+ if ok && existingShard != shard {
log.Infof("Cluster %s has changed shard from %d to %d", k, existingShard, shard)
- case !ok:
+ } else if !ok {
log.Infof("Cluster %s has been assigned to shard %d", k, shard)
- default:
+ } else {
log.Debugf("Cluster %s has not changed shard", k)
}
sharding.Shards[k] = shard
@@ -190,11 +188,11 @@ func hasShardingUpdates(old, new *v1alpha1.Cluster) bool {
}
// A read lock should be acquired before calling getClusterAccessor.
-func (sharding *ClusterSharding) getClusterAccessor() clusterAccessor {
+func (d *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(sharding.Clusters))
- for _, c := range sharding.Clusters {
+ clusters := make([]*v1alpha1.Cluster, 0, len(d.Clusters))
+ for _, c := range d.Clusters {
clusters = append(clusters, c)
}
return clusters
@@ -202,10 +200,10 @@ func (sharding *ClusterSharding) getClusterAccessor() clusterAccessor {
}
// A read lock should be acquired before calling getAppAccessor.
-func (sharding *ClusterSharding) getAppAccessor() appAccessor {
+func (d *ClusterSharding) getAppAccessor() appAccessor {
return func() []*v1alpha1.Application {
- apps := make([]*v1alpha1.Application, 0, len(sharding.Apps))
- for _, a := range sharding.Apps {
+ apps := make([]*v1alpha1.Application, 0, len(d.Apps))
+ for _, a := range d.Apps {
apps = append(apps, a)
}
return apps
@@ -265,14 +263,3 @@ func (sharding *ClusterSharding) GetAppDistribution() map[string]int {
}
return appDistribution
}
-
-// UpdateShard will update the shard of ClusterSharding when the shard has changed.
-func (sharding *ClusterSharding) UpdateShard(shard int) bool {
- if shard != sharding.Shard {
- sharding.lock.RLock()
- sharding.Shard = shard
- sharding.lock.RUnlock()
- return true
- }
- return false
-}
diff --git a/controller/sharding/cache_test.go b/controller/sharding/cache_test.go
index b8d5962703..34318ec259 100644
--- a/controller/sharding/cache_test.go
+++ b/controller/sharding/cache_test.go
@@ -5,8 +5,8 @@ import (
"github.com/stretchr/testify/assert"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- dbmocks "github.com/argoproj/argo-cd/v3/util/db/mocks"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+ dbmocks "github.com/argoproj/argo-cd/v2/util/db/mocks"
)
func setupTestSharding(shard int, replicas int) *ClusterSharding {
diff --git a/controller/sharding/consistent/consistent.go b/controller/sharding/consistent/consistent.go
index 9055525eb6..bb9a549926 100644
--- a/controller/sharding/consistent/consistent.go
+++ b/controller/sharding/consistent/consistent.go
@@ -138,14 +138,15 @@ func (c *Consistent) GetLeast(client string) (string, error) {
foundItem = c.clients.Min()
}
key := c.clients.Get(foundItem)
- if key == nil {
+ if key != nil {
+ host := c.servers[key.(item).value]
+ if c.loadOK(host) {
+ return host, nil
+ }
+ h = key.(item).value
+ } else {
return client, nil
}
- host := c.servers[key.(item).value]
- if c.loadOK(host) {
- return host, nil
- }
- h = key.(item).value
}
}
diff --git a/controller/sharding/sharding.go b/controller/sharding/sharding.go
index a09cb3d429..e593547b00 100644
--- a/controller/sharding/sharding.go
+++ b/controller/sharding/sharding.go
@@ -3,32 +3,31 @@ package sharding
import (
"context"
"encoding/json"
- stderrors "errors"
"fmt"
"hash/fnv"
"math"
"os"
- "slices"
"sort"
"strconv"
"strings"
"time"
- corev1 "k8s.io/api/core/v1"
+ slices "golang.org/x/exp/slices"
+ v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
- "github.com/argoproj/argo-cd/v3/common"
- "github.com/argoproj/argo-cd/v3/controller/sharding/consistent"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/common"
+ "github.com/argoproj/argo-cd/v2/controller/sharding/consistent"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
log "github.com/sirupsen/logrus"
- apierrors "k8s.io/apimachinery/pkg/api/errors"
+ kubeerrors "k8s.io/apimachinery/pkg/api/errors"
- "github.com/argoproj/argo-cd/v3/util/db"
- "github.com/argoproj/argo-cd/v3/util/env"
- "github.com/argoproj/argo-cd/v3/util/errors"
- "github.com/argoproj/argo-cd/v3/util/settings"
+ "github.com/argoproj/argo-cd/v2/util/db"
+ "github.com/argoproj/argo-cd/v2/util/env"
+ "github.com/argoproj/argo-cd/v2/util/errors"
+ "github.com/argoproj/argo-cd/v2/util/settings"
)
// Make it overridable for testing
@@ -63,7 +62,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.ArgoDB, distributionFunction DistributionFunction, replicas, shard int) ClusterFilterFunction {
+func GetClusterFilter(db db.ArgoDB, distributionFunction DistributionFunction, replicas, shard int) ClusterFilterFunction {
return func(c *v1alpha1.Cluster) bool {
clusterShard := 0
if c != nil && c.Shard != nil {
@@ -122,12 +121,13 @@ 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)
}
}
@@ -148,16 +148,17 @@ 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
@@ -179,21 +180,22 @@ 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
@@ -252,7 +254,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(_ *v1alpha1.Cluster) int { return 0 }
+ return func(c *v1alpha1.Cluster) int { return 0 }
}
// InferShard extracts the shard index based on its hostname.
@@ -308,8 +310,9 @@ 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) {
+ if !kubeerrors.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)
@@ -327,27 +330,28 @@ 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
- }
- // 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)
- }
+ } 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)
+ }
- 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
+ _, err = kubeClient.CoreV1().ConfigMaps(settingsMgr.GetNamespace()).Update(context.Background(), shardMappingCM, metav1.UpdateOptions{})
+ if err != nil {
+ return -1, err
+ }
+ return shard, nil
}
- return shard, nil
}
// getOrUpdateShardNumberForController takes list of shardApplicationControllerMapping and performs computation to find the matching or empty shard number
@@ -415,8 +419,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) (*corev1.ConfigMap, error) {
- shardingCM := &corev1.ConfigMap{
+func generateDefaultShardMappingCM(namespace, hostname string, replicas, shard int) (*v1.ConfigMap, error) {
+ shardingCM := &v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: common.ArgoCDAppControllerShardConfigMapName,
Namespace: namespace,
@@ -464,10 +468,11 @@ func GetClusterSharding(kubeClient kubernetes.Interface, settingsMgr *settings.S
return nil, fmt.Errorf("(dynamic cluster distribution) failed to get app controller deployment: %w", err)
}
- if appControllerDeployment == nil || appControllerDeployment.Spec.Replicas == nil {
- return nil, stderrors.New("(dynamic cluster distribution) failed to get app controller deployment replica count")
+ if appControllerDeployment != nil && appControllerDeployment.Spec.Replicas != nil {
+ replicasCount = int(*appControllerDeployment.Spec.Replicas)
+ } else {
+ return nil, fmt.Errorf("(dynamic cluster distribution) failed to get app controller deployment replica count")
}
- replicasCount = int(*appControllerDeployment.Spec.Replicas)
} else {
replicasCount = env.ParseNumFromEnv(common.EnvControllerReplicas, 0, 0, math.MaxInt32)
}
@@ -481,14 +486,11 @@ 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 && !apierrors.IsConflict(err) {
+ if err != nil && !kubeerrors.IsConflict(err) {
err = fmt.Errorf("unable to get shard due to error updating the sharding config map: %w", err)
break
}
- // if `err == nil`, should not log the following warning message
- if err != nil {
- log.Warnf("conflict when getting shard from shard mapping configMap. Retrying (%d/3)", i)
- }
+ log.Warnf("conflict when getting shard from shard mapping configMap. Retrying (%d/3)", i)
}
errors.CheckError(err)
} else {
diff --git a/controller/sharding/sharding_test.go b/controller/sharding/sharding_test.go
index 64aa2010aa..b76741be92 100644
--- a/controller/sharding/sharding_test.go
+++ b/controller/sharding/sharding_test.go
@@ -1,6 +1,7 @@
package sharding
import (
+ "context"
"encoding/json"
"errors"
"fmt"
@@ -13,16 +14,16 @@ import (
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
appsv1 "k8s.io/api/apps/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/runtime"
kubefake "k8s.io/client-go/kubernetes/fake"
"sigs.k8s.io/yaml"
- "github.com/argoproj/argo-cd/v3/common"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- dbmocks "github.com/argoproj/argo-cd/v3/util/db/mocks"
- "github.com/argoproj/argo-cd/v3/util/settings"
+ "github.com/argoproj/argo-cd/v2/common"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+ dbmocks "github.com/argoproj/argo-cd/v2/util/db/mocks"
+ "github.com/argoproj/argo-cd/v2/util/settings"
)
func TestGetShardByID_NotEmptyID(t *testing.T) {
@@ -390,8 +391,12 @@ func TestGetShardByIndexModuloReplicasCountDistributionFunction(t *testing.T) {
shardForCluster1 := distributionFunction(&cluster1)
shardForCluster2 := distributionFunction(&cluster2)
- assert.Equal(t, expectedShardForCluster1, shardForCluster1, "Expected shard for cluster1 to be %d but got %d", expectedShardForCluster1, shardForCluster1)
- assert.Equal(t, expectedShardForCluster2, shardForCluster2, "Expected shard for cluster2 to be %d but got %d", expectedShardForCluster2, shardForCluster2)
+ if shardForCluster1 != expectedShardForCluster1 {
+ t.Errorf("Expected shard for cluster1 to be %d but got %d", expectedShardForCluster1, shardForCluster1)
+ }
+ if shardForCluster2 != expectedShardForCluster2 {
+ t.Errorf("Expected shard for cluster2 to be %d but got %d", expectedShardForCluster2, shardForCluster2)
+ }
}
func TestInferShard(t *testing.T) {
@@ -492,7 +497,7 @@ func Test_generateDefaultShardMappingCM_NoPredefinedShard(t *testing.T) {
expectedMappingCM, err := json.Marshal(expectedMapping)
require.NoError(t, err)
- expectedShadingCM := &corev1.ConfigMap{
+ expectedShadingCM := &v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: common.ArgoCDAppControllerShardConfigMapName,
Namespace: "test",
@@ -527,7 +532,7 @@ func Test_generateDefaultShardMappingCM_PredefinedShard(t *testing.T) {
expectedMappingCM, err := json.Marshal(expectedMapping)
require.NoError(t, err)
- expectedShadingCM := &corev1.ConfigMap{
+ expectedShadingCM := &v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: common.ArgoCDAppControllerShardConfigMapName,
Namespace: "test",
@@ -816,7 +821,7 @@ func TestGetClusterSharding(t *testing.T) {
objects := append([]runtime.Object{}, deployment, deploymentMultiReplicas)
kubeclientset := kubefake.NewSimpleClientset(objects...)
- settingsMgr := settings.NewSettingsManager(t.Context(), kubeclientset, "argocd", settings.WithRepoOrClusterChangedHandler(func() {
+ settingsMgr := settings.NewSettingsManager(context.TODO(), kubeclientset, "argocd", settings.WithRepoOrClusterChangedHandler(func() {
}))
testCases := []struct {
@@ -953,7 +958,7 @@ func TestGetClusterSharding(t *testing.T) {
useDynamicSharding: true,
expectedShard: 0,
expectedReplicas: 1,
- expectedErr: errors.New("(dynamic cluster distribution) failed to get app controller deployment: deployments.apps \"missing-deployment\" not found"),
+ expectedErr: fmt.Errorf("(dynamic cluster distribution) failed to get app controller deployment: deployments.apps \"missing-deployment\" not found"),
},
}
@@ -970,7 +975,11 @@ func TestGetClusterSharding(t *testing.T) {
}
if tc.expectedErr != nil {
- assert.EqualError(t, err, tc.expectedErr.Error())
+ if err != nil {
+ assert.Equal(t, tc.expectedErr.Error(), err.Error())
+ } else {
+ t.Errorf("Expected error %v but got nil", tc.expectedErr)
+ }
} else {
require.NoError(t, err)
}
@@ -979,37 +988,35 @@ func TestGetClusterSharding(t *testing.T) {
}
func TestAppAwareCache(t *testing.T) {
- _, _, cluster1, cluster2, cluster3, cluster4, cluster5 := createTestClusters()
+ _, db, cluster1, cluster2, cluster3, cluster4, cluster5 := createTestClusters()
_, app1, app2, app3, app4, app5 := createTestApps()
- clusterList := getClusterPointers([]v1alpha1.Cluster{cluster1, cluster2, cluster3, cluster4, cluster5})
- appList := getAppPointers([]v1alpha1.Application{app1, app2, app3, app4, app5})
+ clusterSharding := NewClusterSharding(db, 0, 1, "legacy")
- getClusters := func() []*v1alpha1.Cluster { return clusterList }
- getApps := func() []*v1alpha1.Application { return appList }
+ clusterList := &v1alpha1.ClusterList{Items: []v1alpha1.Cluster{cluster1, cluster2, cluster3, cluster4, cluster5}}
+ appList := &v1alpha1.ApplicationList{Items: []v1alpha1.Application{app1, app2, app3, app4, app5}}
+ clusterSharding.Init(clusterList, appList)
- appDistribution := getAppDistribution(getClusters, getApps)
+ appDistribution := clusterSharding.GetAppDistribution()
- assert.Equal(t, int64(2), appDistribution["cluster1"])
- assert.Equal(t, int64(2), appDistribution["cluster2"])
- assert.Equal(t, int64(1), appDistribution["cluster3"])
+ assert.Equal(t, 2, appDistribution["cluster1"])
+ assert.Equal(t, 2, appDistribution["cluster2"])
+ assert.Equal(t, 1, appDistribution["cluster3"])
app6 := createApp("app6", "cluster4")
- appList = append(appList, &app6)
+ clusterSharding.AddApp(&app6)
app1Update := createApp("app1", "cluster2")
- // replace app 1
- appList[0] = &app1Update
+ clusterSharding.UpdateApp(&app1Update)
- // Remove app 3
- appList = append(appList[:2], appList[3:]...)
+ clusterSharding.DeleteApp(&app3)
- appDistribution = getAppDistribution(getClusters, getApps)
+ appDistribution = clusterSharding.GetAppDistribution()
- assert.Equal(t, int64(1), appDistribution["cluster1"])
- assert.Equal(t, int64(2), appDistribution["cluster2"])
- assert.Equal(t, int64(1), appDistribution["cluster3"])
- assert.Equal(t, int64(1), appDistribution["cluster4"])
+ assert.Equal(t, 1, appDistribution["cluster1"])
+ assert.Equal(t, 2, appDistribution["cluster2"])
+ assert.Equal(t, 1, appDistribution["cluster3"])
+ assert.Equal(t, 1, appDistribution["cluster4"])
}
func createTestApps() (appAccessor, v1alpha1.Application, v1alpha1.Application, v1alpha1.Application, v1alpha1.Application, v1alpha1.Application) {
diff --git a/controller/sharding/shuffle_test.go b/controller/sharding/shuffle_test.go
index 0fa6f5f548..390b822545 100644
--- a/controller/sharding/shuffle_test.go
+++ b/controller/sharding/shuffle_test.go
@@ -9,9 +9,9 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
- "github.com/argoproj/argo-cd/v3/common"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- dbmocks "github.com/argoproj/argo-cd/v3/util/db/mocks"
+ "github.com/argoproj/argo-cd/v2/common"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+ dbmocks "github.com/argoproj/argo-cd/v2/util/db/mocks"
)
func TestLargeShuffle(t *testing.T) {
diff --git a/controller/sort_delete_test.go b/controller/sort_delete_test.go
index e3a89c0280..83b90ec47d 100644
--- a/controller/sort_delete_test.go
+++ b/controller/sort_delete_test.go
@@ -4,8 +4,6 @@ import (
"reflect"
"testing"
- "github.com/stretchr/testify/assert"
-
"github.com/argoproj/gitops-engine/pkg/sync/common"
. "github.com/argoproj/gitops-engine/pkg/utils/testing"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
@@ -24,8 +22,9 @@ func TestFilterObjectsForDeletion(t *testing.T) {
for _, tt := range tests {
in := sliceOfObjectsWithSyncWaves(tt.input)
need := sliceOfObjectsWithSyncWaves(tt.want)
- got := FilterObjectsForDeletion(in)
- assert.True(t, reflect.DeepEqual(got, need), "Received unexpected objects for deletion")
+ if got := FilterObjectsForDeletion(in); !reflect.DeepEqual(got, need) {
+ t.Errorf("Received unexpected objects for deletion = %v, want %v", got, need)
+ }
}
}
diff --git a/controller/state.go b/controller/state.go
index b0a63d1b81..054b5d51a1 100644
--- a/controller/state.go
+++ b/controller/state.go
@@ -11,7 +11,7 @@ import (
"time"
synccommon "github.com/argoproj/gitops-engine/pkg/sync/common"
- corev1 "k8s.io/api/core/v1"
+ v1 "k8s.io/api/core/v1"
"github.com/argoproj/gitops-engine/pkg/diff"
"github.com/argoproj/gitops-engine/pkg/health"
@@ -28,26 +28,25 @@ import (
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/tools/cache"
- "github.com/argoproj/argo-cd/v3/common"
- statecache "github.com/argoproj/argo-cd/v3/controller/cache"
- "github.com/argoproj/argo-cd/v3/controller/metrics"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- appclientset "github.com/argoproj/argo-cd/v3/pkg/client/clientset/versioned"
- "github.com/argoproj/argo-cd/v3/reposerver/apiclient"
- applog "github.com/argoproj/argo-cd/v3/util/app/log"
- "github.com/argoproj/argo-cd/v3/util/app/path"
- "github.com/argoproj/argo-cd/v3/util/argo"
- argodiff "github.com/argoproj/argo-cd/v3/util/argo/diff"
- "github.com/argoproj/argo-cd/v3/util/argo/normalizers"
- appstatecache "github.com/argoproj/argo-cd/v3/util/cache/appstate"
- "github.com/argoproj/argo-cd/v3/util/db"
- "github.com/argoproj/argo-cd/v3/util/gpg"
- utilio "github.com/argoproj/argo-cd/v3/util/io"
- "github.com/argoproj/argo-cd/v3/util/settings"
- "github.com/argoproj/argo-cd/v3/util/stats"
+ "github.com/argoproj/argo-cd/v2/common"
+ statecache "github.com/argoproj/argo-cd/v2/controller/cache"
+ "github.com/argoproj/argo-cd/v2/controller/metrics"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+ appclientset "github.com/argoproj/argo-cd/v2/pkg/client/clientset/versioned"
+ "github.com/argoproj/argo-cd/v2/reposerver/apiclient"
+ "github.com/argoproj/argo-cd/v2/util/app/path"
+ "github.com/argoproj/argo-cd/v2/util/argo"
+ argodiff "github.com/argoproj/argo-cd/v2/util/argo/diff"
+ "github.com/argoproj/argo-cd/v2/util/argo/normalizers"
+ appstatecache "github.com/argoproj/argo-cd/v2/util/cache/appstate"
+ "github.com/argoproj/argo-cd/v2/util/db"
+ "github.com/argoproj/argo-cd/v2/util/gpg"
+ "github.com/argoproj/argo-cd/v2/util/io"
+ "github.com/argoproj/argo-cd/v2/util/settings"
+ "github.com/argoproj/argo-cd/v2/util/stats"
)
-var ErrCompareStateRepo = errors.New("failed to get repo objects")
+var CompareStateRepoError = errors.New("failed to get repo objects")
type resourceInfoProviderStub struct{}
@@ -78,7 +77,7 @@ type AppStateManager interface {
// comparisonResult holds the state of an application after the reconciliation
type comparisonResult struct {
syncStatus *v1alpha1.SyncStatus
- healthStatus health.HealthStatusCode
+ healthStatus *v1alpha1.HealthStatus
resources []v1alpha1.ResourceStatus
managedResources []managedResource
reconciliationResult sync.ReconciliationResult
@@ -97,7 +96,7 @@ func (res *comparisonResult) GetSyncStatus() *v1alpha1.SyncStatus {
return res.syncStatus
}
-func (res *comparisonResult) GetHealthStatus() health.HealthStatusCode {
+func (res *comparisonResult) GetHealthStatus() *v1alpha1.HealthStatus {
return res.healthStatus
}
@@ -164,35 +163,25 @@ func (m *appStateManager) GetRepoObjs(app *v1alpha1.Application, sources []v1alp
return nil, nil, false, fmt.Errorf("failed to get Helm settings: %w", err)
}
- trackingMethod, err := m.settingsMgr.GetTrackingMethod()
- if err != nil {
- return nil, nil, false, fmt.Errorf("failed to get trackingMethod: %w", err)
- }
-
installationID, err := m.settingsMgr.GetInstallationID()
if err != nil {
return nil, nil, false, fmt.Errorf("failed to get installation ID: %w", err)
}
- destCluster, err := argo.GetDestinationCluster(context.Background(), app.Spec.Destination, m.db)
- if err != nil {
- return nil, nil, false, fmt.Errorf("failed to get destination cluster: %w", err)
- }
-
ts.AddCheckpoint("build_options_ms")
var serverVersion string
var apiResources []kubeutil.APIResourceInfo
if sendRuntimeState {
- serverVersion, apiResources, err = m.liveStateCache.GetVersionsInfo(destCluster)
+ serverVersion, apiResources, err = m.liveStateCache.GetVersionsInfo(app.Spec.Destination.Server)
if err != nil {
- return nil, nil, false, fmt.Errorf("failed to get cluster version for cluster %q: %w", destCluster.Server, err)
+ return nil, nil, false, fmt.Errorf("failed to get cluster version for cluster %q: %w", app.Spec.Destination.Server, err)
}
}
conn, repoClient, err := m.repoClientset.NewRepoServerClient()
if err != nil {
return nil, nil, false, fmt.Errorf("failed to connect to repo server: %w", err)
}
- defer utilio.Close(conn)
+ defer io.Close(conn)
manifestInfos := make([]*apiclient.ManifestResponse, 0)
targetObjs := make([]*unstructured.Unstructured, 0)
@@ -255,7 +244,7 @@ func (m *appStateManager) GetRepoObjs(app *v1alpha1.Application, sources []v1alp
ApplicationSource: &source,
KubeVersion: serverVersion,
ApiVersions: apiVersions,
- TrackingMethod: trackingMethod,
+ TrackingMethod: string(argo.GetTrackingMethod(m.settingsMgr)),
RefSources: refSources,
HasMultipleSources: app.Spec.HasMultipleSources(),
InstallationID: installationID,
@@ -292,7 +281,7 @@ func (m *appStateManager) GetRepoObjs(app *v1alpha1.Application, sources []v1alp
ApiVersions: apiVersions,
VerifySignature: verifySignature,
HelmRepoCreds: permittedHelmCredentials,
- TrackingMethod: trackingMethod,
+ TrackingMethod: string(argo.GetTrackingMethod(m.settingsMgr)),
EnabledSourceTypes: enabledSourceTypes,
HelmOptions: helmOptions,
HasMultipleSources: app.Spec.HasMultipleSources(),
@@ -315,7 +304,7 @@ func (m *appStateManager) GetRepoObjs(app *v1alpha1.Application, sources []v1alp
}
ts.AddCheckpoint("manifests_ms")
- logCtx := log.WithFields(applog.GetAppLogFields(app))
+ logCtx := log.WithField("application", app.QualifiedName())
for k, v := range ts.Timings() {
logCtx = logCtx.WithField(k, v.Milliseconds())
}
@@ -337,7 +326,7 @@ func (m *appStateManager) ResolveGitRevision(repoURL string, revision string) (s
if err != nil {
return "", fmt.Errorf("failed to connect to repo server: %w", err)
}
- defer utilio.Close(conn)
+ defer io.Close(conn)
repo, err := m.db.GetRepository(context.Background(), repoURL, "")
if err != nil {
@@ -416,53 +405,26 @@ func DeduplicateTargetObjects(
return result, conditions, nil
}
-// normalizeClusterScopeTracking will set the app instance tracking metadata on malformed cluster-scoped resources where
-// metadata.namespace is not empty. The repo-server doesn't know which resources are cluster-scoped, so it may apply
-// an incorrect tracking annotation using the metadata.namespace. This function will correct that.
-func normalizeClusterScopeTracking(targetObjs []*unstructured.Unstructured, infoProvider kubeutil.ResourceInfoProvider, setAppInstance func(*unstructured.Unstructured) error) error {
- for i := len(targetObjs) - 1; i >= 0; i-- {
- targetObj := targetObjs[i]
- if targetObj == nil {
- continue
- }
- gvk := targetObj.GroupVersionKind()
- if !kubeutil.IsNamespacedOrUnknown(infoProvider, gvk.GroupKind()) {
- if targetObj.GetNamespace() != "" {
- targetObj.SetNamespace("")
- err := setAppInstance(targetObj)
- if err != nil {
- return fmt.Errorf("failed to set app instance label on cluster-scoped resource %s/%s: %w", gvk.String(), targetObj.GetName(), err)
- }
- }
- }
- }
- return nil
-}
-
// getComparisonSettings will return the system level settings related to the
// diff/normalization process.
-func (m *appStateManager) getComparisonSettings() (string, map[string]v1alpha1.ResourceOverride, *settings.ResourcesFilter, string, string, error) {
+func (m *appStateManager) getComparisonSettings() (string, map[string]v1alpha1.ResourceOverride, *settings.ResourcesFilter, string, error) {
resourceOverrides, err := m.settingsMgr.GetResourceOverrides()
if err != nil {
- return "", nil, nil, "", "", err
+ return "", nil, nil, "", err
}
appLabelKey, err := m.settingsMgr.GetAppInstanceLabelKey()
if err != nil {
- return "", nil, nil, "", "", err
+ return "", nil, nil, "", err
}
resFilter, err := m.settingsMgr.GetResourcesFilter()
if err != nil {
- return "", nil, nil, "", "", err
+ return "", nil, nil, "", err
}
installationID, err := m.settingsMgr.GetInstallationID()
if err != nil {
- return "", nil, nil, "", "", err
+ return "", nil, nil, "", err
}
- trackingMethod, err := m.settingsMgr.GetTrackingMethod()
- if err != nil {
- return "", nil, nil, "", "", err
- }
- return appLabelKey, resourceOverrides, resFilter, installationID, trackingMethod, nil
+ return appLabelKey, resourceOverrides, resFilter, installationID, nil
}
// verifyGnuPGSignature verifies the result of a GnuPG operation for a given git
@@ -513,7 +475,7 @@ func isManagedNamespace(ns *unstructured.Unstructured, app *v1alpha1.Application
// revision and overrides in the app spec.
func (m *appStateManager) CompareAppState(app *v1alpha1.Application, project *v1alpha1.AppProject, revisions []string, sources []v1alpha1.ApplicationSource, noCache bool, noRevisionCache bool, localManifests []string, hasMultipleSources bool, rollback bool) (*comparisonResult, error) {
ts := stats.NewTimingStats()
- appLabelKey, resourceOverrides, resFilter, installationID, trackingMethod, err := m.getComparisonSettings()
+ appLabelKey, resourceOverrides, resFilter, installationID, err := m.getComparisonSettings()
ts.AddCheckpoint("settings_ms")
@@ -526,32 +488,31 @@ func (m *appStateManager) CompareAppState(app *v1alpha1.Application, project *v1
Status: v1alpha1.SyncStatusCodeUnknown,
Revisions: revisions,
},
- healthStatus: health.HealthStatusUnknown,
+ healthStatus: &v1alpha1.HealthStatus{Status: health.HealthStatusUnknown},
+ }, nil
+ } else {
+ return &comparisonResult{
+ syncStatus: &v1alpha1.SyncStatus{
+ ComparedTo: app.Spec.BuildComparedToStatus(),
+ Status: v1alpha1.SyncStatusCodeUnknown,
+ Revision: revisions[0],
+ },
+ healthStatus: &v1alpha1.HealthStatus{Status: health.HealthStatusUnknown},
}, nil
}
- return &comparisonResult{
- syncStatus: &v1alpha1.SyncStatus{
- ComparedTo: app.Spec.BuildComparedToStatus(),
- Status: v1alpha1.SyncStatusCodeUnknown,
- Revision: revisions[0],
- },
- healthStatus: health.HealthStatusUnknown,
- }, nil
}
// When signature keys are defined in the project spec, we need to verify the signature on the Git revision
- verifySignature := len(project.Spec.SignatureKeys) > 0 && gpg.IsGPGEnabled()
+ verifySignature := false
+ if len(project.Spec.SignatureKeys) > 0 && gpg.IsGPGEnabled() {
+ verifySignature = true
+ }
// do best effort loading live and target state to present as much information about app state as possible
failedToLoadObjs := false
conditions := make([]v1alpha1.ApplicationCondition, 0)
- destCluster, err := argo.GetDestinationCluster(context.Background(), app.Spec.Destination, m.db)
- if err != nil {
- return nil, err
- }
-
- logCtx := log.WithFields(applog.GetAppLogFields(app))
+ logCtx := log.WithField("application", app.QualifiedName())
logCtx.Infof("Comparing app state (cluster: %s, namespace: %s)", app.Spec.Destination.Server, app.Spec.Destination.Namespace)
var targetObjs []*unstructured.Unstructured
@@ -575,19 +536,19 @@ func (m *appStateManager) CompareAppState(app *v1alpha1.Application, project *v1
targetObjs, manifestInfos, revisionUpdated, err = m.GetRepoObjs(app, sources, appLabelKey, revisions, noCache, noRevisionCache, verifySignature, project, rollback, true)
if err != nil {
targetObjs = make([]*unstructured.Unstructured, 0)
- msg := "Failed to load target state: " + err.Error()
+ msg := fmt.Sprintf("Failed to load target state: %s", err.Error())
conditions = append(conditions, v1alpha1.ApplicationCondition{Type: v1alpha1.ApplicationConditionComparisonError, Message: msg, LastTransitionTime: &now})
if firstSeen, ok := m.repoErrorCache.Load(app.Name); ok {
if time.Since(firstSeen.(time.Time)) <= m.repoErrorGracePeriod && !noRevisionCache {
// if first seen is less than grace period and it's not a Level 3 comparison,
// ignore error and short circuit
logCtx.Debugf("Ignoring repo error %v, already encountered error in grace period", err.Error())
- return nil, ErrCompareStateRepo
+ return nil, CompareStateRepoError
}
} else if !noRevisionCache {
logCtx.Debugf("Ignoring repo error %v, new occurrence", err.Error())
m.repoErrorCache.Store(app.Name, time.Now())
- return nil, ErrCompareStateRepo
+ return nil, CompareStateRepoError
}
failedToLoadObjs = true
} else {
@@ -605,7 +566,7 @@ func (m *appStateManager) CompareAppState(app *v1alpha1.Application, project *v1
targetObjs, err = unmarshalManifests(localManifests)
if err != nil {
targetObjs = make([]*unstructured.Unstructured, 0)
- msg := "Failed to load local manifests: " + err.Error()
+ msg := fmt.Sprintf("Failed to load local manifests: %s", err.Error())
conditions = append(conditions, v1alpha1.ApplicationCondition{Type: v1alpha1.ApplicationConditionComparisonError, Message: msg, LastTransitionTime: &now})
failedToLoadObjs = true
}
@@ -616,30 +577,20 @@ func (m *appStateManager) CompareAppState(app *v1alpha1.Application, project *v1
ts.AddCheckpoint("git_ms")
var infoProvider kubeutil.ResourceInfoProvider
- infoProvider, err = m.liveStateCache.GetClusterCache(destCluster)
+ infoProvider, err = m.liveStateCache.GetClusterCache(app.Spec.Destination.Server)
if err != nil {
infoProvider = &resourceInfoProviderStub{}
}
-
- err = normalizeClusterScopeTracking(targetObjs, infoProvider, func(u *unstructured.Unstructured) error {
- return m.resourceTracking.SetAppInstance(u, appLabelKey, app.InstanceName(m.namespace), app.Spec.Destination.Namespace, v1alpha1.TrackingMethod(trackingMethod), installationID)
- })
- if err != nil {
- msg := "Failed to normalize cluster-scoped resource tracking: " + err.Error()
- conditions = append(conditions, v1alpha1.ApplicationCondition{Type: v1alpha1.ApplicationConditionComparisonError, Message: msg, LastTransitionTime: &now})
- }
-
targetObjs, dedupConditions, err := DeduplicateTargetObjects(app.Spec.Destination.Namespace, targetObjs, infoProvider)
if err != nil {
- msg := "Failed to deduplicate target state: " + err.Error()
+ msg := fmt.Sprintf("Failed to deduplicate target state: %s", err.Error())
conditions = append(conditions, v1alpha1.ApplicationCondition{Type: v1alpha1.ApplicationConditionComparisonError, Message: msg, LastTransitionTime: &now})
}
conditions = append(conditions, dedupConditions...)
-
for i := len(targetObjs) - 1; i >= 0; i-- {
targetObj := targetObjs[i]
gvk := targetObj.GroupVersionKind()
- if resFilter.IsExcludedResource(gvk.Group, gvk.Kind, destCluster.Server) {
+ if resFilter.IsExcludedResource(gvk.Group, gvk.Kind, app.Spec.Destination.Server) {
targetObjs = append(targetObjs[:i], targetObjs[i+1:]...)
conditions = append(conditions, v1alpha1.ApplicationCondition{
Type: v1alpha1.ApplicationConditionExcludedResourceWarning,
@@ -657,18 +608,19 @@ func (m *appStateManager) CompareAppState(app *v1alpha1.Application, project *v1
}
ts.AddCheckpoint("dedup_ms")
- liveObjByKey, err := m.liveStateCache.GetManagedLiveObjs(destCluster, app, targetObjs)
+ liveObjByKey, err := m.liveStateCache.GetManagedLiveObjs(app, targetObjs)
if err != nil {
liveObjByKey = make(map[kubeutil.ResourceKey]*unstructured.Unstructured)
- msg := "Failed to load live state: " + err.Error()
+ msg := fmt.Sprintf("Failed to load live state: %s", err.Error())
conditions = append(conditions, v1alpha1.ApplicationCondition{Type: v1alpha1.ApplicationConditionComparisonError, Message: msg, LastTransitionTime: &now})
failedToLoadObjs = true
}
logCtx.Debugf("Retrieved live manifests")
+
// filter out all resources which are not permitted in the application project
for k, v := range liveObjByKey {
- permitted, err := project.IsLiveResourcePermitted(v, destCluster, func(project string) ([]*v1alpha1.Cluster, error) {
+ permitted, err := project.IsLiveResourcePermitted(v, app.Spec.Destination.Server, app.Spec.Destination.Name, func(project string) ([]*v1alpha1.Cluster, error) {
clusters, err := m.db.GetProjectClusters(context.TODO(), project)
if err != nil {
return nil, fmt.Errorf("failed to get clusters for project %q: %w", project, err)
@@ -687,9 +639,11 @@ func (m *appStateManager) CompareAppState(app *v1alpha1.Application, project *v1
}
}
+ trackingMethod := argo.GetTrackingMethod(m.settingsMgr)
+
for _, liveObj := range liveObjByKey {
if liveObj != nil {
- appInstanceName := m.resourceTracking.GetAppName(liveObj, appLabelKey, v1alpha1.TrackingMethod(trackingMethod), installationID)
+ appInstanceName := m.resourceTracking.GetAppName(liveObj, appLabelKey, trackingMethod, installationID)
if appInstanceName != "" && appInstanceName != app.InstanceName(m.namespace) {
fqInstanceName := strings.ReplaceAll(appInstanceName, "_", "/")
conditions = append(conditions, v1alpha1.ApplicationCondition{
@@ -712,7 +666,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 := &corev1.Namespace{TypeMeta: metav1.TypeMeta{APIVersion: "v1", Kind: kubeutil.NamespaceKind}, ObjectMeta: metav1.ObjectMeta{Name: liveObj.GetName()}}
+ nsSpec := &v1.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})
@@ -777,7 +731,7 @@ func (m *appStateManager) CompareAppState(app *v1alpha1.Application, project *v1
diffConfigBuilder.WithIgnoreMutationWebhook(false)
}
- gvkParser, err := m.getGVKParser(destCluster)
+ gvkParser, err := m.getGVKParser(app.Spec.Destination.Server)
if err != nil {
conditions = append(conditions, v1alpha1.ApplicationCondition{Type: v1alpha1.ApplicationConditionUnknownError, Message: err.Error(), LastTransitionTime: &now})
}
@@ -787,7 +741,7 @@ func (m *appStateManager) CompareAppState(app *v1alpha1.Application, project *v1
diffConfigBuilder.WithServerSideDiff(serverSideDiff)
if serverSideDiff {
- applier, cleanup, err := m.getServerSideDiffDryRunApplier(destCluster)
+ applier, cleanup, err := m.getServerSideDiffDryRunApplier(app.Spec.Destination.Server)
if err != nil {
log.Errorf("CompareAppState error getting server side diff dry run applier: %s", err)
conditions = append(conditions, v1alpha1.ApplicationCondition{Type: v1alpha1.ApplicationConditionUnknownError, Message: err.Error(), LastTransitionTime: &now})
@@ -809,7 +763,7 @@ func (m *appStateManager) CompareAppState(app *v1alpha1.Application, project *v1
if err != nil {
diffResults = &diff.DiffResultList{}
failedToLoadObjs = true
- msg := "Failed to compare desired state to live state: " + err.Error()
+ msg := fmt.Sprintf("Failed to compare desired state to live state: %s", err.Error())
conditions = append(conditions, v1alpha1.ApplicationCondition{Type: v1alpha1.ApplicationConditionComparisonError, Message: msg, LastTransitionTime: &now})
}
ts.AddCheckpoint("diff_ms")
@@ -828,7 +782,7 @@ func (m *appStateManager) CompareAppState(app *v1alpha1.Application, project *v1
}
gvk := obj.GroupVersionKind()
- isSelfReferencedObj := m.isSelfReferencedObj(liveObj, targetObj, app.GetName(), v1alpha1.TrackingMethod(trackingMethod), installationID)
+ isSelfReferencedObj := m.isSelfReferencedObj(liveObj, targetObj, app.GetName(), appLabelKey, trackingMethod, installationID)
resState := v1alpha1.ResourceStatus{
Namespace: obj.GetNamespace(),
@@ -861,13 +815,12 @@ func (m *appStateManager) CompareAppState(app *v1alpha1.Application, project *v1
// namespace from being pruned.
isManagedNs := isManagedNamespace(targetObj, app) && liveObj == nil
- switch {
- case resState.Hook || ignore.Ignore(obj) || (targetObj != nil && hookutil.Skip(targetObj)) || !isSelfReferencedObj:
+ if resState.Hook || ignore.Ignore(obj) || (targetObj != nil && hookutil.Skip(targetObj)) || !isSelfReferencedObj {
// For resource hooks, skipped resources or objects that may have
// been created by another controller with annotations copied from
// the source object, don't store sync status, and do not affect
// overall sync status
- case !isManagedNs && (diffResult.Modified || targetObj == nil || liveObj == nil):
+ } else if !isManagedNs && (diffResult.Modified || targetObj == nil || liveObj == nil) {
// Set resource state to OutOfSync since one of the following is true:
// * target and live resource are different
// * target resource not defined and live resource is extra
@@ -875,14 +828,14 @@ func (m *appStateManager) CompareAppState(app *v1alpha1.Application, project *v1
resState.Status = v1alpha1.SyncStatusCodeOutOfSync
// we ignore the status if the obj needs pruning AND we have the annotation
needsPruning := targetObj == nil && liveObj != nil
- if !needsPruning || !resourceutil.HasAnnotationOption(obj, common.AnnotationCompareOptions, "IgnoreExtraneous") {
+ if !(needsPruning && resourceutil.HasAnnotationOption(obj, common.AnnotationCompareOptions, "IgnoreExtraneous")) {
syncCode = v1alpha1.SyncStatusCodeOutOfSync
}
- default:
+ } else {
resState.Status = v1alpha1.SyncStatusCodeSynced
}
// set unknown status to all resource that are not permitted in the app project
- isNamespaced, err := m.liveStateCache.IsNamespaced(destCluster, gvk.GroupKind())
+ isNamespaced, err := m.liveStateCache.IsNamespaced(app.Spec.Destination.Server, gvk.GroupKind())
if !project.IsGroupKindPermitted(gvk.GroupKind(), isNamespaced && err == nil) {
resState.Status = v1alpha1.SyncStatusCodeUnknown
}
@@ -952,7 +905,7 @@ func (m *appStateManager) CompareAppState(app *v1alpha1.Application, project *v1
healthStatus, err := setApplicationHealth(managedResources, resourceSummaries, resourceOverrides, app, m.persistResourceHealth)
if err != nil {
- conditions = append(conditions, v1alpha1.ApplicationCondition{Type: v1alpha1.ApplicationConditionComparisonError, Message: "error setting app health: " + err.Error(), LastTransitionTime: &now})
+ conditions = append(conditions, v1alpha1.ApplicationCondition{Type: v1alpha1.ApplicationConditionComparisonError, Message: fmt.Sprintf("error setting app health: %s", err.Error()), LastTransitionTime: &now})
}
// Git has already performed the signature verification via its GPG interface, and the result is available
@@ -1046,6 +999,20 @@ func specEqualsCompareTo(spec v1alpha1.ApplicationSpec, comparedTo v1alpha1.Comp
// Make a copy to be sure we don't mutate the original.
specCopy := spec.DeepCopy()
currentSpec := specCopy.BuildComparedToStatus()
+
+ // The spec might have been augmented to include both server and name, so change it to match the comparedTo before
+ // comparing.
+ if comparedTo.Destination.Server == "" {
+ currentSpec.Destination.Server = ""
+ }
+ if comparedTo.Destination.Name == "" {
+ currentSpec.Destination.Name = ""
+ }
+
+ // Set IsServerInferred to false on both, because that field is not important for comparison.
+ comparedTo.Destination.SetIsServerInferred(false)
+ currentSpec.Destination.SetIsServerInferred(false)
+
return reflect.DeepEqual(comparedTo, currentSpec)
}
@@ -1145,14 +1112,14 @@ 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 string, trackingMethod v1alpha1.TrackingMethod, installationID string) bool {
+func (m *appStateManager) isSelfReferencedObj(live, config *unstructured.Unstructured, appName, appLabelKey string, trackingMethod v1alpha1.TrackingMethod, installationID string) bool {
if live == nil {
return true
}
// If tracking method doesn't contain required metadata for this check,
// we are not able to determine and just assume the object to be managed.
- if trackingMethod == v1alpha1.TrackingMethodLabel {
+ if trackingMethod == argo.TrackingMethodLabel {
return true
}
@@ -1178,7 +1145,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, trackingMethod, installationID)
+ appInstance := m.resourceTracking.GetAppInstance(live, appLabelKey, trackingMethod, installationID)
if appInstance != nil {
return isSelfReferencedObj(live, *appInstance)
}
diff --git a/controller/state_test.go b/controller/state_test.go
index 3795238c33..4c6ab69f5f 100644
--- a/controller/state_test.go
+++ b/controller/state_test.go
@@ -2,41 +2,38 @@ package controller
import (
"encoding/json"
- "errors"
+ "fmt"
"os"
"testing"
"time"
- "dario.cat/mergo"
- cachemocks "github.com/argoproj/gitops-engine/pkg/cache/mocks"
"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"
- "github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
- appsv1 "k8s.io/api/apps/v1"
+ v1 "k8s.io/api/apps/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"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
- "github.com/argoproj/argo-cd/v3/common"
- "github.com/argoproj/argo-cd/v3/controller/testdata"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- "github.com/argoproj/argo-cd/v3/reposerver/apiclient"
- "github.com/argoproj/argo-cd/v3/test"
+ "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"
)
// TestCompareAppStateEmpty tests comparison when both git and live have no objects
func TestCompareAppStateEmpty(t *testing.T) {
- t.Parallel()
-
app := newFakeApp()
data := fakeData{
manifestResponse: &apiclient.ManifestResponse{
@@ -48,7 +45,7 @@ func TestCompareAppStateEmpty(t *testing.T) {
managedLiveObjs: make(map[kube.ResourceKey]*unstructured.Unstructured),
}
ctrl := newFakeController(&data, nil)
- sources := make([]v1alpha1.ApplicationSource, 0)
+ sources := make([]argoappv1.ApplicationSource, 0)
sources = append(sources, app.Spec.GetSource())
revisions := make([]string, 0)
revisions = append(revisions, "")
@@ -56,7 +53,7 @@ func TestCompareAppStateEmpty(t *testing.T) {
require.NoError(t, err)
assert.NotNil(t, compRes)
assert.NotNil(t, compRes.syncStatus)
- assert.Equal(t, v1alpha1.SyncStatusCodeSynced, compRes.syncStatus.Status)
+ assert.Equal(t, argoappv1.SyncStatusCodeSynced, compRes.syncStatus.Status)
assert.Empty(t, compRes.resources)
assert.Empty(t, compRes.managedResources)
assert.Empty(t, app.Status.Conditions)
@@ -65,32 +62,32 @@ func TestCompareAppStateEmpty(t *testing.T) {
// TestCompareAppStateRepoError tests the case when CompareAppState notices a repo error
func TestCompareAppStateRepoError(t *testing.T) {
app := newFakeApp()
- ctrl := newFakeController(&fakeData{manifestResponses: make([]*apiclient.ManifestResponse, 3)}, errors.New("test repo error"))
- sources := make([]v1alpha1.ApplicationSource, 0)
+ ctrl := newFakeController(&fakeData{manifestResponses: make([]*apiclient.ManifestResponse, 3)}, fmt.Errorf("test repo error"))
+ sources := make([]argoappv1.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)
assert.Nil(t, compRes)
- require.EqualError(t, err, ErrCompareStateRepo.Error())
+ require.EqualError(t, err, CompareStateRepoError.Error())
// expect to still get compare state error to as inside grace period
compRes, err = ctrl.appStateManager.CompareAppState(app, &defaultProj, revisions, sources, false, false, nil, false, false)
assert.Nil(t, compRes)
- require.EqualError(t, err, ErrCompareStateRepo.Error())
+ require.EqualError(t, err, CompareStateRepoError.Error())
time.Sleep(10 * time.Second)
// expect to not get error as outside of grace period, but status should be unknown
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, v1alpha1.SyncStatusCodeUnknown, compRes.syncStatus.Status)
+ assert.Equal(t, argoappv1.SyncStatusCodeUnknown, compRes.syncStatus.Status)
}
// TestCompareAppStateNamespaceMetadataDiffers tests comparison when managed namespace metadata differs
func TestCompareAppStateNamespaceMetadataDiffers(t *testing.T) {
app := newFakeApp()
- app.Spec.SyncPolicy.ManagedNamespaceMetadata = &v1alpha1.ManagedNamespaceMetadata{
+ app.Spec.SyncPolicy.ManagedNamespaceMetadata = &argoappv1.ManagedNamespaceMetadata{
Labels: map[string]string{
"foo": "bar",
},
@@ -98,8 +95,8 @@ func TestCompareAppStateNamespaceMetadataDiffers(t *testing.T) {
"foo": "bar",
},
}
- app.Status.OperationState = &v1alpha1.OperationState{
- SyncResult: &v1alpha1.SyncOperationResult{},
+ app.Status.OperationState = &argoappv1.OperationState{
+ SyncResult: &argoappv1.SyncOperationResult{},
}
data := fakeData{
@@ -112,7 +109,7 @@ func TestCompareAppStateNamespaceMetadataDiffers(t *testing.T) {
managedLiveObjs: make(map[kube.ResourceKey]*unstructured.Unstructured),
}
ctrl := newFakeController(&data, nil)
- sources := make([]v1alpha1.ApplicationSource, 0)
+ sources := make([]argoappv1.ApplicationSource, 0)
sources = append(sources, app.Spec.GetSource())
revisions := make([]string, 0)
revisions = append(revisions, "")
@@ -120,7 +117,7 @@ func TestCompareAppStateNamespaceMetadataDiffers(t *testing.T) {
require.NoError(t, err)
assert.NotNil(t, compRes)
assert.NotNil(t, compRes.syncStatus)
- assert.Equal(t, v1alpha1.SyncStatusCodeOutOfSync, compRes.syncStatus.Status)
+ assert.Equal(t, argoappv1.SyncStatusCodeOutOfSync, compRes.syncStatus.Status)
assert.Empty(t, compRes.resources)
assert.Empty(t, compRes.managedResources)
assert.Empty(t, app.Status.Conditions)
@@ -134,7 +131,7 @@ func TestCompareAppStateNamespaceMetadataDiffersToManifest(t *testing.T) {
ns.SetAnnotations(map[string]string{"bar": "bat"})
app := newFakeApp()
- app.Spec.SyncPolicy.ManagedNamespaceMetadata = &v1alpha1.ManagedNamespaceMetadata{
+ app.Spec.SyncPolicy.ManagedNamespaceMetadata = &argoappv1.ManagedNamespaceMetadata{
Labels: map[string]string{
"foo": "bar",
},
@@ -142,8 +139,8 @@ func TestCompareAppStateNamespaceMetadataDiffersToManifest(t *testing.T) {
"foo": "bar",
},
}
- app.Status.OperationState = &v1alpha1.OperationState{
- SyncResult: &v1alpha1.SyncOperationResult{},
+ app.Status.OperationState = &argoappv1.OperationState{
+ SyncResult: &argoappv1.SyncOperationResult{},
}
liveNs := ns.DeepCopy()
@@ -161,7 +158,7 @@ func TestCompareAppStateNamespaceMetadataDiffersToManifest(t *testing.T) {
},
}
ctrl := newFakeController(&data, nil)
- sources := make([]v1alpha1.ApplicationSource, 0)
+ sources := make([]argoappv1.ApplicationSource, 0)
sources = append(sources, app.Spec.GetSource())
revisions := make([]string, 0)
revisions = append(revisions, "")
@@ -169,7 +166,7 @@ func TestCompareAppStateNamespaceMetadataDiffersToManifest(t *testing.T) {
require.NoError(t, err)
assert.NotNil(t, compRes)
assert.NotNil(t, compRes.syncStatus)
- assert.Equal(t, v1alpha1.SyncStatusCodeOutOfSync, compRes.syncStatus.Status)
+ assert.Equal(t, argoappv1.SyncStatusCodeOutOfSync, compRes.syncStatus.Status)
assert.Len(t, compRes.resources, 1)
assert.Len(t, compRes.managedResources, 1)
assert.NotNil(t, compRes.diffResultList)
@@ -195,7 +192,7 @@ func TestCompareAppStateNamespaceMetadata(t *testing.T) {
ns.SetAnnotations(map[string]string{"bar": "bat"})
app := newFakeApp()
- app.Spec.SyncPolicy.ManagedNamespaceMetadata = &v1alpha1.ManagedNamespaceMetadata{
+ app.Spec.SyncPolicy.ManagedNamespaceMetadata = &argoappv1.ManagedNamespaceMetadata{
Labels: map[string]string{
"foo": "bar",
},
@@ -203,8 +200,8 @@ func TestCompareAppStateNamespaceMetadata(t *testing.T) {
"foo": "bar",
},
}
- app.Status.OperationState = &v1alpha1.OperationState{
- SyncResult: &v1alpha1.SyncOperationResult{},
+ app.Status.OperationState = &argoappv1.OperationState{
+ SyncResult: &argoappv1.SyncOperationResult{},
}
data := fakeData{
@@ -219,7 +216,7 @@ func TestCompareAppStateNamespaceMetadata(t *testing.T) {
},
}
ctrl := newFakeController(&data, nil)
- sources := make([]v1alpha1.ApplicationSource, 0)
+ sources := make([]argoappv1.ApplicationSource, 0)
sources = append(sources, app.Spec.GetSource())
revisions := make([]string, 0)
revisions = append(revisions, "")
@@ -227,7 +224,7 @@ func TestCompareAppStateNamespaceMetadata(t *testing.T) {
require.NoError(t, err)
assert.NotNil(t, compRes)
assert.NotNil(t, compRes.syncStatus)
- assert.Equal(t, v1alpha1.SyncStatusCodeOutOfSync, compRes.syncStatus.Status)
+ assert.Equal(t, argoappv1.SyncStatusCodeOutOfSync, compRes.syncStatus.Status)
assert.Len(t, compRes.resources, 1)
assert.Len(t, compRes.managedResources, 1)
assert.NotNil(t, compRes.diffResultList)
@@ -247,7 +244,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 = &v1alpha1.ManagedNamespaceMetadata{
+ app.Spec.SyncPolicy.ManagedNamespaceMetadata = &argoappv1.ManagedNamespaceMetadata{
Labels: map[string]string{
"foo": "bar",
},
@@ -255,9 +252,9 @@ func TestCompareAppStateNamespaceMetadataIsTheSame(t *testing.T) {
"foo": "bar",
},
}
- app.Status.OperationState = &v1alpha1.OperationState{
- SyncResult: &v1alpha1.SyncOperationResult{
- ManagedNamespaceMetadata: &v1alpha1.ManagedNamespaceMetadata{
+ app.Status.OperationState = &argoappv1.OperationState{
+ SyncResult: &argoappv1.SyncOperationResult{
+ ManagedNamespaceMetadata: &argoappv1.ManagedNamespaceMetadata{
Labels: map[string]string{
"foo": "bar",
},
@@ -278,7 +275,7 @@ func TestCompareAppStateNamespaceMetadataIsTheSame(t *testing.T) {
managedLiveObjs: make(map[kube.ResourceKey]*unstructured.Unstructured),
}
ctrl := newFakeController(&data, nil)
- sources := make([]v1alpha1.ApplicationSource, 0)
+ sources := make([]argoappv1.ApplicationSource, 0)
sources = append(sources, app.Spec.GetSource())
revisions := make([]string, 0)
revisions = append(revisions, "")
@@ -286,7 +283,7 @@ func TestCompareAppStateNamespaceMetadataIsTheSame(t *testing.T) {
require.NoError(t, err)
assert.NotNil(t, compRes)
assert.NotNil(t, compRes.syncStatus)
- assert.Equal(t, v1alpha1.SyncStatusCodeSynced, compRes.syncStatus.Status)
+ assert.Equal(t, argoappv1.SyncStatusCodeSynced, compRes.syncStatus.Status)
assert.Empty(t, compRes.resources)
assert.Empty(t, compRes.managedResources)
assert.Empty(t, app.Status.Conditions)
@@ -306,7 +303,7 @@ func TestCompareAppStateMissing(t *testing.T) {
managedLiveObjs: make(map[kube.ResourceKey]*unstructured.Unstructured),
}
ctrl := newFakeController(&data, nil)
- sources := make([]v1alpha1.ApplicationSource, 0)
+ sources := make([]argoappv1.ApplicationSource, 0)
sources = append(sources, app.Spec.GetSource())
revisions := make([]string, 0)
revisions = append(revisions, "")
@@ -314,7 +311,7 @@ func TestCompareAppStateMissing(t *testing.T) {
require.NoError(t, err)
assert.NotNil(t, compRes)
assert.NotNil(t, compRes.syncStatus)
- assert.Equal(t, v1alpha1.SyncStatusCodeOutOfSync, compRes.syncStatus.Status)
+ assert.Equal(t, argoappv1.SyncStatusCodeOutOfSync, compRes.syncStatus.Status)
assert.Len(t, compRes.resources, 1)
assert.Len(t, compRes.managedResources, 1)
assert.Empty(t, app.Status.Conditions)
@@ -338,14 +335,14 @@ func TestCompareAppStateExtra(t *testing.T) {
},
}
ctrl := newFakeController(&data, nil)
- sources := make([]v1alpha1.ApplicationSource, 0)
+ sources := make([]argoappv1.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, v1alpha1.SyncStatusCodeOutOfSync, compRes.syncStatus.Status)
+ assert.Equal(t, argoappv1.SyncStatusCodeOutOfSync, compRes.syncStatus.Status)
assert.Len(t, compRes.resources, 1)
assert.Len(t, compRes.managedResources, 1)
assert.Empty(t, app.Status.Conditions)
@@ -369,14 +366,14 @@ func TestCompareAppStateHook(t *testing.T) {
managedLiveObjs: make(map[kube.ResourceKey]*unstructured.Unstructured),
}
ctrl := newFakeController(&data, nil)
- sources := make([]v1alpha1.ApplicationSource, 0)
+ sources := make([]argoappv1.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, v1alpha1.SyncStatusCodeSynced, compRes.syncStatus.Status)
+ assert.Equal(t, argoappv1.SyncStatusCodeSynced, compRes.syncStatus.Status)
assert.Empty(t, compRes.resources)
assert.Empty(t, compRes.managedResources)
assert.Len(t, compRes.reconciliationResult.Hooks, 1)
@@ -401,14 +398,14 @@ func TestCompareAppStateSkipHook(t *testing.T) {
managedLiveObjs: make(map[kube.ResourceKey]*unstructured.Unstructured),
}
ctrl := newFakeController(&data, nil)
- sources := make([]v1alpha1.ApplicationSource, 0)
+ sources := make([]argoappv1.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, v1alpha1.SyncStatusCodeSynced, compRes.syncStatus.Status)
+ assert.Equal(t, argoappv1.SyncStatusCodeSynced, compRes.syncStatus.Status)
assert.Len(t, compRes.resources, 1)
assert.Len(t, compRes.managedResources, 1)
assert.Empty(t, compRes.reconciliationResult.Hooks)
@@ -432,7 +429,7 @@ func TestCompareAppStateCompareOptionIgnoreExtraneous(t *testing.T) {
}
ctrl := newFakeController(&data, nil)
- sources := make([]v1alpha1.ApplicationSource, 0)
+ sources := make([]argoappv1.ApplicationSource, 0)
sources = append(sources, app.Spec.GetSource())
revisions := make([]string, 0)
revisions = append(revisions, "")
@@ -440,7 +437,7 @@ func TestCompareAppStateCompareOptionIgnoreExtraneous(t *testing.T) {
require.NoError(t, err)
assert.NotNil(t, compRes)
- assert.Equal(t, v1alpha1.SyncStatusCodeSynced, compRes.syncStatus.Status)
+ assert.Equal(t, argoappv1.SyncStatusCodeSynced, compRes.syncStatus.Status)
assert.Empty(t, compRes.resources)
assert.Empty(t, compRes.managedResources)
assert.Empty(t, app.Status.Conditions)
@@ -465,7 +462,7 @@ func TestCompareAppStateExtraHook(t *testing.T) {
},
}
ctrl := newFakeController(&data, nil)
- sources := make([]v1alpha1.ApplicationSource, 0)
+ sources := make([]argoappv1.ApplicationSource, 0)
sources = append(sources, app.Spec.GetSource())
revisions := make([]string, 0)
revisions = append(revisions, "")
@@ -473,7 +470,7 @@ func TestCompareAppStateExtraHook(t *testing.T) {
require.NoError(t, err)
assert.NotNil(t, compRes)
- assert.Equal(t, v1alpha1.SyncStatusCodeSynced, compRes.syncStatus.Status)
+ assert.Equal(t, argoappv1.SyncStatusCodeSynced, compRes.syncStatus.Status)
assert.Len(t, compRes.resources, 1)
assert.Len(t, compRes.managedResources, 1)
assert.Empty(t, compRes.reconciliationResult.Hooks)
@@ -583,7 +580,7 @@ func TestCompareAppStateDuplicatedNamespacedResources(t *testing.T) {
},
}
ctrl := newFakeController(&data, nil)
- sources := make([]v1alpha1.ApplicationSource, 0)
+ sources := make([]argoappv1.ApplicationSource, 0)
sources = append(sources, app.Spec.GetSource())
revisions := make([]string, 0)
revisions = append(revisions, "")
@@ -593,15 +590,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, v1alpha1.ApplicationConditionRepeatedResourceWarning, app.Status.Conditions[0].Type)
+ assert.Equal(t, argoappv1.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 = &v1alpha1.SyncPolicy{
- ManagedNamespaceMetadata: &v1alpha1.ManagedNamespaceMetadata{
+ app.Spec.SyncPolicy = &argoappv1.SyncPolicy{
+ ManagedNamespaceMetadata: &argoappv1.ManagedNamespaceMetadata{
Labels: nil,
Annotations: nil,
},
@@ -640,14 +637,14 @@ func TestCompareAppStateManagedNamespaceMetadataWithLiveNsDoesNotGetPruned(t *te
assert.Len(t, compRes.managedResources, 1)
}
-var defaultProj = v1alpha1.AppProject{
+var defaultProj = argoappv1.AppProject{
ObjectMeta: metav1.ObjectMeta{
Name: "default",
Namespace: test.FakeArgoCDNamespace,
},
- Spec: v1alpha1.AppProjectSpec{
+ Spec: argoappv1.AppProjectSpec{
SourceRepos: []string{"*"},
- Destinations: []v1alpha1.ApplicationDestination{
+ Destinations: []argoappv1.ApplicationDestination{
{
Server: "*",
Namespace: "*",
@@ -659,10 +656,10 @@ var defaultProj = v1alpha1.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{v1alpha1.AnnotationKeyManifestGeneratePaths: "."})
- app.Status.Sync = v1alpha1.SyncStatus{
+ app.SetAnnotations(map[string]string{argoappv1.AnnotationKeyManifestGeneratePaths: "."})
+ app.Status.Sync = argoappv1.SyncStatus{
Revision: "abc123",
- Status: v1alpha1.SyncStatusCodeSynced,
+ Status: argoappv1.SyncStatusCodeSynced,
}
data := fakeData{
@@ -681,13 +678,13 @@ 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, v1alpha1.SyncStatusCodeSynced, compRes.syncStatus.Status)
+ assert.Equal(t, argoappv1.SyncStatusCodeSynced, compRes.syncStatus.Status)
assert.Equal(t, "abc123", compRes.syncStatus.Revision)
}
func TestSetHealth(t *testing.T) {
app := newFakeApp()
- deployment := kube.MustToUnstructured(&appsv1.Deployment{
+ deployment := kube.MustToUnstructured(&v1.Deployment{
TypeMeta: metav1.TypeMeta{
APIVersion: "apps/v1",
Kind: "Deployment",
@@ -710,20 +707,21 @@ func TestSetHealth(t *testing.T) {
},
}, nil)
- sources := make([]v1alpha1.ApplicationSource, 0)
+ sources := make([]argoappv1.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.Equal(t, health.HealthStatusHealthy, compRes.healthStatus)
+ assert.Equal(t, health.HealthStatusHealthy, compRes.healthStatus.Status)
+ assert.Equal(t, app.Status.Health.LastTransitionTime, compRes.healthStatus.LastTransitionTime)
}
func TestPreserveStatusTimestamp(t *testing.T) {
timestamp := metav1.Now()
app := newFakeAppWithHealthAndTime(health.HealthStatusHealthy, timestamp)
- deployment := kube.MustToUnstructured(&appsv1.Deployment{
+ deployment := kube.MustToUnstructured(&v1.Deployment{
TypeMeta: metav1.TypeMeta{
APIVersion: "apps/v1",
Kind: "Deployment",
@@ -746,20 +744,21 @@ func TestPreserveStatusTimestamp(t *testing.T) {
},
}, nil)
- sources := make([]v1alpha1.ApplicationSource, 0)
+ sources := make([]argoappv1.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.Equal(t, health.HealthStatusHealthy, compRes.healthStatus)
+ assert.Equal(t, health.HealthStatusHealthy, compRes.healthStatus.Status)
+ assert.Equal(t, timestamp, *compRes.healthStatus.LastTransitionTime)
}
func TestSetHealthSelfReferencedApp(t *testing.T) {
app := newFakeApp()
unstructuredApp := kube.MustToUnstructured(app)
- deployment := kube.MustToUnstructured(&appsv1.Deployment{
+ deployment := kube.MustToUnstructured(&v1.Deployment{
TypeMeta: metav1.TypeMeta{
APIVersion: "apps/v1",
Kind: "Deployment",
@@ -783,34 +782,35 @@ func TestSetHealthSelfReferencedApp(t *testing.T) {
},
}, nil)
- sources := make([]v1alpha1.ApplicationSource, 0)
+ sources := make([]argoappv1.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.Equal(t, health.HealthStatusHealthy, compRes.healthStatus)
+ assert.Equal(t, health.HealthStatusHealthy, compRes.healthStatus.Status)
+ assert.Equal(t, app.Status.Health.LastTransitionTime, compRes.healthStatus.LastTransitionTime)
}
func TestSetManagedResourcesWithOrphanedResources(t *testing.T) {
proj := defaultProj.DeepCopy()
- proj.Spec.OrphanedResources = &v1alpha1.OrphanedResourcesMonitorSettings{}
+ proj.Spec.OrphanedResources = &argoappv1.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: v1alpha1.ResourceNode{
- ResourceRef: v1alpha1.ResourceRef{Kind: kube.DeploymentKind, Name: "guestbook", Namespace: app.Namespace},
+ ResourceNode: argoappv1.ResourceNode{
+ ResourceRef: argoappv1.ResourceRef{Kind: kube.DeploymentKind, Name: "guestbook", Namespace: app.Namespace},
},
AppName: "",
},
},
}, nil)
- tree, err := ctrl.setAppManagedResources(&v1alpha1.Cluster{Server: "test", Name: "test"}, app, &comparisonResult{managedResources: make([]managedResource, 0)})
+ tree, err := ctrl.setAppManagedResources(app, &comparisonResult{managedResources: make([]managedResource, 0)})
require.NoError(t, err)
assert.Len(t, tree.OrphanedNodes, 1)
@@ -820,7 +820,7 @@ func TestSetManagedResourcesWithOrphanedResources(t *testing.T) {
func TestSetManagedResourcesWithResourcesOfAnotherApp(t *testing.T) {
proj := defaultProj.DeepCopy()
- proj.Spec.OrphanedResources = &v1alpha1.OrphanedResourcesMonitorSettings{}
+ proj.Spec.OrphanedResources = &argoappv1.OrphanedResourcesMonitorSettings{}
app1 := newFakeApp()
app1.Name = "app1"
@@ -831,15 +831,15 @@ 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: v1alpha1.ResourceNode{
- ResourceRef: v1alpha1.ResourceRef{Kind: kube.DeploymentKind, Name: "guestbook", Namespace: app2.Namespace},
+ ResourceNode: argoappv1.ResourceNode{
+ ResourceRef: argoappv1.ResourceRef{Kind: kube.DeploymentKind, Name: "guestbook", Namespace: app2.Namespace},
},
AppName: "app2",
},
},
}, nil)
- tree, err := ctrl.setAppManagedResources(&v1alpha1.Cluster{Server: "test", Name: "test"}, app1, &comparisonResult{managedResources: make([]managedResource, 0)})
+ tree, err := ctrl.setAppManagedResources(app1, &comparisonResult{managedResources: make([]managedResource, 0)})
require.NoError(t, err)
assert.Empty(t, tree.OrphanedNodes)
@@ -847,7 +847,7 @@ func TestSetManagedResourcesWithResourcesOfAnotherApp(t *testing.T) {
func TestReturnUnknownComparisonStateOnSettingLoadError(t *testing.T) {
proj := defaultProj.DeepCopy()
- proj.Spec.OrphanedResources = &v1alpha1.OrphanedResourcesMonitorSettings{}
+ proj.Spec.OrphanedResources = &argoappv1.OrphanedResourcesMonitorSettings{}
app := newFakeApp()
@@ -858,20 +858,21 @@ func TestReturnUnknownComparisonStateOnSettingLoadError(t *testing.T) {
},
}, nil)
- sources := make([]v1alpha1.ApplicationSource, 0)
+ sources := make([]argoappv1.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.Equal(t, health.HealthStatusUnknown, compRes.healthStatus)
- assert.Equal(t, v1alpha1.SyncStatusCodeUnknown, compRes.syncStatus.Status)
+ assert.Equal(t, health.HealthStatusUnknown, compRes.healthStatus.Status)
+ assert.Equal(t, app.Status.Health.LastTransitionTime, compRes.healthStatus.LastTransitionTime)
+ assert.Equal(t, argoappv1.SyncStatusCodeUnknown, compRes.syncStatus.Status)
}
func TestSetManagedResourcesKnownOrphanedResourceExceptions(t *testing.T) {
proj := defaultProj.DeepCopy()
- proj.Spec.OrphanedResources = &v1alpha1.OrphanedResourcesMonitorSettings{}
+ proj.Spec.OrphanedResources = &argoappv1.OrphanedResourcesMonitorSettings{}
proj.Spec.SourceNamespaces = []string{"default"}
app := newFakeApp()
@@ -881,18 +882,18 @@ func TestSetManagedResourcesKnownOrphanedResourceExceptions(t *testing.T) {
apps: []runtime.Object{app, proj},
namespacedResources: map[kube.ResourceKey]namespacedResource{
kube.NewResourceKey("apps", kube.DeploymentKind, app.Namespace, "guestbook"): {
- ResourceNode: v1alpha1.ResourceNode{ResourceRef: v1alpha1.ResourceRef{Group: "apps", Kind: kube.DeploymentKind, Name: "guestbook", Namespace: app.Namespace}},
+ ResourceNode: argoappv1.ResourceNode{ResourceRef: argoappv1.ResourceRef{Group: "apps", Kind: kube.DeploymentKind, Name: "guestbook", Namespace: app.Namespace}},
},
kube.NewResourceKey("", kube.ServiceAccountKind, app.Namespace, "default"): {
- ResourceNode: v1alpha1.ResourceNode{ResourceRef: v1alpha1.ResourceRef{Kind: kube.ServiceAccountKind, Name: "default", Namespace: app.Namespace}},
+ ResourceNode: argoappv1.ResourceNode{ResourceRef: argoappv1.ResourceRef{Kind: kube.ServiceAccountKind, Name: "default", Namespace: app.Namespace}},
},
kube.NewResourceKey("", kube.ServiceKind, app.Namespace, "kubernetes"): {
- ResourceNode: v1alpha1.ResourceNode{ResourceRef: v1alpha1.ResourceRef{Kind: kube.ServiceAccountKind, Name: "kubernetes", Namespace: app.Namespace}},
+ ResourceNode: argoappv1.ResourceNode{ResourceRef: argoappv1.ResourceRef{Kind: kube.ServiceAccountKind, Name: "kubernetes", Namespace: app.Namespace}},
},
},
}, nil)
- tree, err := ctrl.setAppManagedResources(&v1alpha1.Cluster{Server: "test", Name: "test"}, app, &comparisonResult{managedResources: make([]managedResource, 0)})
+ tree, err := ctrl.setAppManagedResources(app, &comparisonResult{managedResources: make([]managedResource, 0)})
require.NoError(t, err)
assert.Len(t, tree.OrphanedNodes, 1)
@@ -906,14 +907,11 @@ func Test_appStateManager_persistRevisionHistory(t *testing.T) {
}, nil)
manager := ctrl.appStateManager.(*appStateManager)
setRevisionHistoryLimit := func(value int) {
- if value < 0 {
- value = 0
- }
i := int64(value)
app.Spec.RevisionHistoryLimit = &i
}
addHistory := func() {
- err := manager.persistRevisionHistory(app, "my-revision", v1alpha1.ApplicationSource{}, []string{}, []v1alpha1.ApplicationSource{}, false, metav1.Time{}, v1alpha1.OperationInitiator{})
+ err := manager.persistRevisionHistory(app, "my-revision", argoappv1.ApplicationSource{}, []string{}, []argoappv1.ApplicationSource{}, false, metav1.Time{}, v1alpha1.OperationInitiator{})
require.NoError(t, err)
}
addHistory()
@@ -949,14 +947,9 @@ 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", v1alpha1.ApplicationSource{}, []string{}, []v1alpha1.ApplicationSource{}, false, metav1NowTime, v1alpha1.OperationInitiator{})
+ err := manager.persistRevisionHistory(app, "my-revision", argoappv1.ApplicationSource{}, []string{}, []argoappv1.ApplicationSource{}, false, metav1NowTime, v1alpha1.OperationInitiator{})
require.NoError(t, err)
assert.Equal(t, app.Status.History.LastRevisionHistory().DeployStartedAt, &metav1NowTime)
-
- // negative limit to 0
- setRevisionHistoryLimit(-1)
- addHistory()
- assert.Empty(t, app.Status.History)
}
// helper function to read contents of a file to string
@@ -969,20 +962,20 @@ func mustReadFile(path string) string {
return string(b)
}
-var signedProj = v1alpha1.AppProject{
+var signedProj = argoappv1.AppProject{
ObjectMeta: metav1.ObjectMeta{
Name: "default",
Namespace: test.FakeArgoCDNamespace,
},
- Spec: v1alpha1.AppProjectSpec{
+ Spec: argoappv1.AppProjectSpec{
SourceRepos: []string{"*"},
- Destinations: []v1alpha1.ApplicationDestination{
+ Destinations: []argoappv1.ApplicationDestination{
{
Server: "*",
Namespace: "*",
},
},
- SignatureKeys: []v1alpha1.SignatureKey{
+ SignatureKeys: []argoappv1.SignatureKey{
{
KeyID: "4AEE18F83AFDEB23",
},
@@ -1007,7 +1000,7 @@ func TestSignedResponseNoSignatureRequired(t *testing.T) {
managedLiveObjs: make(map[kube.ResourceKey]*unstructured.Unstructured),
}
ctrl := newFakeController(&data, nil)
- sources := make([]v1alpha1.ApplicationSource, 0)
+ sources := make([]argoappv1.ApplicationSource, 0)
sources = append(sources, app.Spec.GetSource())
revisions := make([]string, 0)
revisions = append(revisions, "")
@@ -1015,7 +1008,7 @@ func TestSignedResponseNoSignatureRequired(t *testing.T) {
require.NoError(t, err)
assert.NotNil(t, compRes)
assert.NotNil(t, compRes.syncStatus)
- assert.Equal(t, v1alpha1.SyncStatusCodeSynced, compRes.syncStatus.Status)
+ assert.Equal(t, argoappv1.SyncStatusCodeSynced, compRes.syncStatus.Status)
assert.Empty(t, compRes.resources)
assert.Empty(t, compRes.managedResources)
assert.Empty(t, app.Status.Conditions)
@@ -1034,7 +1027,7 @@ func TestSignedResponseNoSignatureRequired(t *testing.T) {
managedLiveObjs: make(map[kube.ResourceKey]*unstructured.Unstructured),
}
ctrl := newFakeController(&data, nil)
- sources := make([]v1alpha1.ApplicationSource, 0)
+ sources := make([]argoappv1.ApplicationSource, 0)
sources = append(sources, app.Spec.GetSource())
revisions := make([]string, 0)
revisions = append(revisions, "")
@@ -1042,7 +1035,7 @@ func TestSignedResponseNoSignatureRequired(t *testing.T) {
require.NoError(t, err)
assert.NotNil(t, compRes)
assert.NotNil(t, compRes.syncStatus)
- assert.Equal(t, v1alpha1.SyncStatusCodeSynced, compRes.syncStatus.Status)
+ assert.Equal(t, argoappv1.SyncStatusCodeSynced, compRes.syncStatus.Status)
assert.Empty(t, compRes.resources)
assert.Empty(t, compRes.managedResources)
assert.Empty(t, app.Status.Conditions)
@@ -1066,7 +1059,7 @@ func TestSignedResponseSignatureRequired(t *testing.T) {
managedLiveObjs: make(map[kube.ResourceKey]*unstructured.Unstructured),
}
ctrl := newFakeController(&data, nil)
- sources := make([]v1alpha1.ApplicationSource, 0)
+ sources := make([]argoappv1.ApplicationSource, 0)
sources = append(sources, app.Spec.GetSource())
revisions := make([]string, 0)
revisions = append(revisions, "")
@@ -1074,7 +1067,7 @@ func TestSignedResponseSignatureRequired(t *testing.T) {
require.NoError(t, err)
assert.NotNil(t, compRes)
assert.NotNil(t, compRes.syncStatus)
- assert.Equal(t, v1alpha1.SyncStatusCodeSynced, compRes.syncStatus.Status)
+ assert.Equal(t, argoappv1.SyncStatusCodeSynced, compRes.syncStatus.Status)
assert.Empty(t, compRes.resources)
assert.Empty(t, compRes.managedResources)
assert.Empty(t, app.Status.Conditions)
@@ -1093,7 +1086,7 @@ func TestSignedResponseSignatureRequired(t *testing.T) {
managedLiveObjs: make(map[kube.ResourceKey]*unstructured.Unstructured),
}
ctrl := newFakeController(&data, nil)
- sources := make([]v1alpha1.ApplicationSource, 0)
+ sources := make([]argoappv1.ApplicationSource, 0)
sources = append(sources, app.Spec.GetSource())
revisions := make([]string, 0)
revisions = append(revisions, "abc123")
@@ -1101,7 +1094,7 @@ func TestSignedResponseSignatureRequired(t *testing.T) {
require.NoError(t, err)
assert.NotNil(t, compRes)
assert.NotNil(t, compRes.syncStatus)
- assert.Equal(t, v1alpha1.SyncStatusCodeSynced, compRes.syncStatus.Status)
+ assert.Equal(t, argoappv1.SyncStatusCodeSynced, compRes.syncStatus.Status)
assert.Empty(t, compRes.resources)
assert.Empty(t, compRes.managedResources)
assert.Len(t, app.Status.Conditions, 1)
@@ -1120,7 +1113,7 @@ func TestSignedResponseSignatureRequired(t *testing.T) {
managedLiveObjs: make(map[kube.ResourceKey]*unstructured.Unstructured),
}
ctrl := newFakeController(&data, nil)
- sources := make([]v1alpha1.ApplicationSource, 0)
+ sources := make([]argoappv1.ApplicationSource, 0)
sources = append(sources, app.Spec.GetSource())
revisions := make([]string, 0)
revisions = append(revisions, "abc123")
@@ -1128,7 +1121,7 @@ func TestSignedResponseSignatureRequired(t *testing.T) {
require.NoError(t, err)
assert.NotNil(t, compRes)
assert.NotNil(t, compRes.syncStatus)
- assert.Equal(t, v1alpha1.SyncStatusCodeSynced, compRes.syncStatus.Status)
+ assert.Equal(t, argoappv1.SyncStatusCodeSynced, compRes.syncStatus.Status)
assert.Empty(t, compRes.resources)
assert.Empty(t, compRes.managedResources)
assert.Len(t, app.Status.Conditions, 1)
@@ -1147,7 +1140,7 @@ func TestSignedResponseSignatureRequired(t *testing.T) {
managedLiveObjs: make(map[kube.ResourceKey]*unstructured.Unstructured),
}
ctrl := newFakeController(&data, nil)
- sources := make([]v1alpha1.ApplicationSource, 0)
+ sources := make([]argoappv1.ApplicationSource, 0)
sources = append(sources, app.Spec.GetSource())
revisions := make([]string, 0)
revisions = append(revisions, "abc123")
@@ -1155,7 +1148,7 @@ func TestSignedResponseSignatureRequired(t *testing.T) {
require.NoError(t, err)
assert.NotNil(t, compRes)
assert.NotNil(t, compRes.syncStatus)
- assert.Equal(t, v1alpha1.SyncStatusCodeSynced, compRes.syncStatus.Status)
+ assert.Equal(t, argoappv1.SyncStatusCodeSynced, compRes.syncStatus.Status)
assert.Empty(t, compRes.resources)
assert.Empty(t, compRes.managedResources)
assert.Len(t, app.Status.Conditions, 1)
@@ -1177,7 +1170,7 @@ func TestSignedResponseSignatureRequired(t *testing.T) {
ctrl := newFakeController(&data, nil)
testProj := signedProj
testProj.Spec.SignatureKeys[0].KeyID = "4AEE18F83AFDEB24"
- sources := make([]v1alpha1.ApplicationSource, 0)
+ sources := make([]argoappv1.ApplicationSource, 0)
sources = append(sources, app.Spec.GetSource())
revisions := make([]string, 0)
revisions = append(revisions, "abc123")
@@ -1185,7 +1178,7 @@ func TestSignedResponseSignatureRequired(t *testing.T) {
require.NoError(t, err)
assert.NotNil(t, compRes)
assert.NotNil(t, compRes.syncStatus)
- assert.Equal(t, v1alpha1.SyncStatusCodeSynced, compRes.syncStatus.Status)
+ assert.Equal(t, argoappv1.SyncStatusCodeSynced, compRes.syncStatus.Status)
assert.Empty(t, compRes.resources)
assert.Empty(t, compRes.managedResources)
assert.Len(t, app.Status.Conditions, 1)
@@ -1207,7 +1200,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([]v1alpha1.ApplicationSource, 0)
+ sources := make([]argoappv1.ApplicationSource, 0)
sources = append(sources, app.Spec.GetSource())
revisions := make([]string, 0)
revisions = append(revisions, "abc123")
@@ -1215,7 +1208,7 @@ func TestSignedResponseSignatureRequired(t *testing.T) {
require.NoError(t, err)
assert.NotNil(t, compRes)
assert.NotNil(t, compRes.syncStatus)
- assert.Equal(t, v1alpha1.SyncStatusCodeUnknown, compRes.syncStatus.Status)
+ assert.Equal(t, argoappv1.SyncStatusCodeUnknown, compRes.syncStatus.Status)
assert.Empty(t, compRes.resources)
assert.Empty(t, compRes.managedResources)
assert.Len(t, app.Status.Conditions, 1)
@@ -1237,7 +1230,7 @@ func TestSignedResponseSignatureRequired(t *testing.T) {
managedLiveObjs: make(map[kube.ResourceKey]*unstructured.Unstructured),
}
ctrl := newFakeController(&data, nil)
- sources := make([]v1alpha1.ApplicationSource, 0)
+ sources := make([]argoappv1.ApplicationSource, 0)
sources = append(sources, app.Spec.GetSource())
revisions := make([]string, 0)
revisions = append(revisions, "abc123")
@@ -1245,7 +1238,7 @@ func TestSignedResponseSignatureRequired(t *testing.T) {
require.NoError(t, err)
assert.NotNil(t, compRes)
assert.NotNil(t, compRes.syncStatus)
- assert.Equal(t, v1alpha1.SyncStatusCodeSynced, compRes.syncStatus.Status)
+ assert.Equal(t, argoappv1.SyncStatusCodeSynced, compRes.syncStatus.Status)
assert.Empty(t, compRes.resources)
assert.Empty(t, compRes.managedResources)
assert.Empty(t, app.Status.Conditions)
@@ -1267,7 +1260,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([]v1alpha1.ApplicationSource, 0)
+ sources := make([]argoappv1.ApplicationSource, 0)
sources = append(sources, app.Spec.GetSource())
revisions := make([]string, 0)
revisions = append(revisions, "abc123")
@@ -1275,7 +1268,7 @@ func TestSignedResponseSignatureRequired(t *testing.T) {
require.NoError(t, err)
assert.NotNil(t, compRes)
assert.NotNil(t, compRes.syncStatus)
- assert.Equal(t, v1alpha1.SyncStatusCodeSynced, compRes.syncStatus.Status)
+ assert.Equal(t, argoappv1.SyncStatusCodeSynced, compRes.syncStatus.Status)
assert.Empty(t, compRes.resources)
assert.Empty(t, compRes.managedResources)
assert.Empty(t, app.Status.Conditions)
@@ -1283,7 +1276,7 @@ func TestSignedResponseSignatureRequired(t *testing.T) {
}
func TestComparisonResult_GetHealthStatus(t *testing.T) {
- status := health.HealthStatusMissing
+ status := &argoappv1.HealthStatus{Status: health.HealthStatusMissing}
res := comparisonResult{
healthStatus: status,
}
@@ -1292,7 +1285,7 @@ func TestComparisonResult_GetHealthStatus(t *testing.T) {
}
func TestComparisonResult_GetSyncStatus(t *testing.T) {
- status := &v1alpha1.SyncStatus{Status: v1alpha1.SyncStatusCodeOutOfSync}
+ status := &argoappv1.SyncStatus{Status: argoappv1.SyncStatusCodeOutOfSync}
res := comparisonResult{
syncStatus: status,
}
@@ -1418,8 +1411,8 @@ func TestIsLiveResourceManaged(t *testing.T) {
configObj := managedObj.DeepCopy()
// then
- assert.True(t, manager.isSelfReferencedObj(managedObj, configObj, appName, v1alpha1.TrackingMethodLabel, ""))
- assert.True(t, manager.isSelfReferencedObj(managedObj, configObj, appName, v1alpha1.TrackingMethodAnnotation, ""))
+ assert.True(t, manager.isSelfReferencedObj(managedObj, configObj, appName, common.AnnotationKeyAppInstance, argo.TrackingMethodLabel, ""))
+ assert.True(t, manager.isSelfReferencedObj(managedObj, configObj, appName, common.AnnotationKeyAppInstance, argo.TrackingMethodAnnotation, ""))
})
t.Run("will return true if tracked with label", func(t *testing.T) {
// given
@@ -1427,43 +1420,43 @@ func TestIsLiveResourceManaged(t *testing.T) {
configObj := managedObjWithLabel.DeepCopy()
// then
- assert.True(t, manager.isSelfReferencedObj(managedObjWithLabel, configObj, appName, v1alpha1.TrackingMethodLabel, ""))
+ assert.True(t, manager.isSelfReferencedObj(managedObjWithLabel, configObj, appName, common.AnnotationKeyAppInstance, 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, v1alpha1.TrackingMethodLabel, ""))
- assert.False(t, manager.isSelfReferencedObj(unmanagedObjWrongName, nil, appName, v1alpha1.TrackingMethodAnnotation, ""))
+ assert.True(t, manager.isSelfReferencedObj(unmanagedObjWrongName, nil, appName, common.AnnotationKeyAppInstance, argo.TrackingMethodLabel, ""))
+ assert.False(t, manager.isSelfReferencedObj(unmanagedObjWrongName, nil, appName, common.AnnotationKeyAppInstance, 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, v1alpha1.TrackingMethodLabel, ""))
- assert.False(t, manager.isSelfReferencedObj(unmanagedObjWrongGroup, nil, appName, v1alpha1.TrackingMethodAnnotation, ""))
+ assert.True(t, manager.isSelfReferencedObj(unmanagedObjWrongGroup, nil, appName, common.AnnotationKeyAppInstance, argo.TrackingMethodLabel, ""))
+ assert.False(t, manager.isSelfReferencedObj(unmanagedObjWrongGroup, nil, appName, common.AnnotationKeyAppInstance, 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, v1alpha1.TrackingMethodLabel, ""))
- assert.False(t, manager.isSelfReferencedObj(unmanagedObjWrongKind, nil, appName, v1alpha1.TrackingMethodAnnotation, ""))
+ assert.True(t, manager.isSelfReferencedObj(unmanagedObjWrongKind, nil, appName, common.AnnotationKeyAppInstance, argo.TrackingMethodLabel, ""))
+ assert.False(t, manager.isSelfReferencedObj(unmanagedObjWrongKind, nil, appName, common.AnnotationKeyAppInstance, 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, v1alpha1.TrackingMethodLabel, ""))
- assert.False(t, manager.isSelfReferencedObj(unmanagedObjWrongNamespace, nil, appName, v1alpha1.TrackingMethodAnnotationAndLabel, ""))
+ assert.True(t, manager.isSelfReferencedObj(unmanagedObjWrongNamespace, nil, appName, common.AnnotationKeyAppInstance, argo.TrackingMethodLabel, ""))
+ assert.False(t, manager.isSelfReferencedObj(unmanagedObjWrongNamespace, nil, appName, common.AnnotationKeyAppInstance, 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, v1alpha1.TrackingMethodAnnotation, ""))
+ assert.True(t, manager.isSelfReferencedObj(nil, nil, appName, common.AnnotationKeyAppInstance, argo.TrackingMethodAnnotation, ""))
})
t.Run("will handle upgrade in desired state APIGroup", func(t *testing.T) {
@@ -1473,7 +1466,7 @@ func TestIsLiveResourceManaged(t *testing.T) {
delete(config.GetAnnotations(), common.AnnotationKeyAppInstance)
// then
- assert.True(t, manager.isSelfReferencedObj(managedWrongAPIGroup, config, appName, v1alpha1.TrackingMethodAnnotation, ""))
+ assert.True(t, manager.isSelfReferencedObj(managedWrongAPIGroup, config, appName, common.AnnotationKeyAppInstance, argo.TrackingMethodAnnotation, ""))
})
}
@@ -1484,8 +1477,8 @@ func TestUseDiffCache(t *testing.T) {
testName string
noCache bool
manifestInfos []*apiclient.ManifestResponse
- sources []v1alpha1.ApplicationSource
- app *v1alpha1.Application
+ sources []argoappv1.ApplicationSource
+ app *argoappv1.Application
manifestRevisions []string
statusRefreshTimeout time.Duration
expectedUseCache bool
@@ -1507,8 +1500,8 @@ func TestUseDiffCache(t *testing.T) {
},
}
}
- sources := func() []v1alpha1.ApplicationSource {
- return []v1alpha1.ApplicationSource{
+ sources := func() []argoappv1.ApplicationSource {
+ return []argoappv1.ApplicationSource{
{
RepoURL: "https://some-repo.com",
Path: "argocd/httpbin",
@@ -1517,41 +1510,41 @@ func TestUseDiffCache(t *testing.T) {
}
}
- app := func(namespace string, revision string, refresh bool, a *v1alpha1.Application) *v1alpha1.Application {
- app := &v1alpha1.Application{
+ app := func(namespace string, revision string, refresh bool, a *argoappv1.Application) *argoappv1.Application {
+ app := &argoappv1.Application{
ObjectMeta: metav1.ObjectMeta{
Name: "httpbin",
Namespace: namespace,
},
- Spec: v1alpha1.ApplicationSpec{
- Source: &v1alpha1.ApplicationSource{
+ Spec: argoappv1.ApplicationSpec{
+ Source: &argoappv1.ApplicationSource{
RepoURL: "https://some-repo.com",
Path: "argocd/httpbin",
TargetRevision: "HEAD",
},
- Destination: v1alpha1.ApplicationDestination{
+ Destination: argoappv1.ApplicationDestination{
Server: "https://kubernetes.default.svc",
Namespace: "httpbin",
},
Project: "default",
- SyncPolicy: &v1alpha1.SyncPolicy{
+ SyncPolicy: &argoappv1.SyncPolicy{
SyncOptions: []string{
"CreateNamespace=true",
"ServerSideApply=true",
},
},
},
- Status: v1alpha1.ApplicationStatus{
- Resources: []v1alpha1.ResourceStatus{},
- Sync: v1alpha1.SyncStatus{
- Status: v1alpha1.SyncStatusCodeSynced,
- ComparedTo: v1alpha1.ComparedTo{
- Source: v1alpha1.ApplicationSource{
+ Status: argoappv1.ApplicationStatus{
+ Resources: []argoappv1.ResourceStatus{},
+ Sync: argoappv1.SyncStatus{
+ Status: argoappv1.SyncStatusCodeSynced,
+ ComparedTo: argoappv1.ComparedTo{
+ Source: argoappv1.ApplicationSource{
RepoURL: "https://some-repo.com",
Path: "argocd/httpbin",
TargetRevision: "HEAD",
},
- Destination: v1alpha1.ApplicationDestination{
+ Destination: argoappv1.ApplicationDestination{
Server: "https://kubernetes.default.svc",
Namespace: "httpbin",
},
@@ -1566,12 +1559,18 @@ func TestUseDiffCache(t *testing.T) {
}
if refresh {
annotations := make(map[string]string)
- annotations[v1alpha1.AnnotationKeyRefresh] = string(v1alpha1.RefreshTypeNormal)
+ annotations[argoappv1.AnnotationKeyRefresh] = string(argoappv1.RefreshTypeNormal)
app.SetAnnotations(annotations)
}
if a != nil {
err := mergo.Merge(app, a, mergo.WithOverride, mergo.WithOverwriteWithEmptyValue)
- require.NoErrorf(t, err, "error merging app")
+ if err != nil {
+ t.Fatalf("error merging app: %s", err)
+ }
+ }
+ if app.Spec.Destination.Name != "" && app.Spec.Destination.Server != "" {
+ // Simulate the controller's process for populating both of these fields.
+ app.Spec.Destination.SetInferredServer(app.Spec.Destination.Server)
}
return app
}
@@ -1604,10 +1603,10 @@ func TestUseDiffCache(t *testing.T) {
noCache: false,
manifestInfos: manifestInfos("rev1"),
sources: sources(),
- app: app("httpbin", "", false, &v1alpha1.Application{
- Spec: v1alpha1.ApplicationSpec{
+ app: app("httpbin", "", false, &argoappv1.Application{
+ Spec: argoappv1.ApplicationSpec{
Source: nil,
- Sources: v1alpha1.ApplicationSources{
+ Sources: argoappv1.ApplicationSources{
{
RepoURL: "multisource repo1",
},
@@ -1616,13 +1615,13 @@ func TestUseDiffCache(t *testing.T) {
},
},
},
- Status: v1alpha1.ApplicationStatus{
- Resources: []v1alpha1.ResourceStatus{},
- Sync: v1alpha1.SyncStatus{
- Status: v1alpha1.SyncStatusCodeSynced,
- ComparedTo: v1alpha1.ComparedTo{
- Source: v1alpha1.ApplicationSource{},
- Sources: v1alpha1.ApplicationSources{
+ Status: argoappv1.ApplicationStatus{
+ Resources: []argoappv1.ResourceStatus{},
+ Sync: argoappv1.SyncStatus{
+ Status: argoappv1.SyncStatusCodeSynced,
+ ComparedTo: argoappv1.ComparedTo{
+ Source: argoappv1.ApplicationSource{},
+ Sources: argoappv1.ApplicationSources{
{
RepoURL: "multisource repo1",
},
@@ -1703,9 +1702,9 @@ func TestUseDiffCache(t *testing.T) {
noCache: false,
manifestInfos: manifestInfos("rev1"),
sources: sources(),
- app: app("httpbin", "rev1", false, &v1alpha1.Application{
- Spec: v1alpha1.ApplicationSpec{
- Source: &v1alpha1.ApplicationSource{
+ app: app("httpbin", "rev1", false, &argoappv1.Application{
+ Spec: argoappv1.ApplicationSpec{
+ Source: &argoappv1.ApplicationSource{
RepoURL: "new-repo",
},
},
@@ -1720,9 +1719,9 @@ func TestUseDiffCache(t *testing.T) {
noCache: false,
manifestInfos: manifestInfos("rev1"),
sources: sources(),
- app: app("httpbin", "rev1", false, &v1alpha1.Application{
- Spec: v1alpha1.ApplicationSpec{
- IgnoreDifferences: []v1alpha1.ResourceIgnoreDifferences{
+ app: app("httpbin", "rev1", false, &argoappv1.Application{
+ Spec: argoappv1.ApplicationSpec{
+ IgnoreDifferences: []argoappv1.ResourceIgnoreDifferences{
{
Group: "app/v1",
Kind: "application",
@@ -1738,6 +1737,44 @@ func TestUseDiffCache(t *testing.T) {
expectedUseCache: false,
serverSideDiff: false,
},
+ {
+ // There are code paths that modify the ApplicationSpec and augment the destination field with both the
+ // destination server and name. Since both fields are populated in the app spec but not in the comparedTo,
+ // we need to make sure we correctly compare the fields and don't miss the cache.
+ testName: "will return true if the app spec destination contains both server and name, but otherwise matches comparedTo",
+ noCache: false,
+ manifestInfos: manifestInfos("rev1"),
+ sources: sources(),
+ app: app("httpbin", "rev1", false, &argoappv1.Application{
+ Spec: argoappv1.ApplicationSpec{
+ Destination: argoappv1.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{
+ Server: "https://kubernetes.default.svc",
+ Namespace: "httpbin",
+ },
+ },
+ Revision: "rev1",
+ },
+ ReconciledAt: &metav1.Time{
+ Time: time.Now().Add(-time.Hour),
+ },
+ },
+ }),
+ manifestRevisions: []string{"rev1"},
+ statusRefreshTimeout: time.Hour * 24,
+ expectedUseCache: true,
+ serverSideDiff: true,
+ },
}
for _, tc := range cases {
@@ -1769,7 +1806,7 @@ func TestCompareAppStateDefaultRevisionUpdated(t *testing.T) {
managedLiveObjs: make(map[kube.ResourceKey]*unstructured.Unstructured),
}
ctrl := newFakeController(&data, nil)
- sources := make([]v1alpha1.ApplicationSource, 0)
+ sources := make([]argoappv1.ApplicationSource, 0)
sources = append(sources, app.Spec.GetSource())
revisions := make([]string, 0)
revisions = append(revisions, "")
@@ -1792,7 +1829,7 @@ func TestCompareAppStateRevisionUpdatedWithHelmSource(t *testing.T) {
managedLiveObjs: make(map[kube.ResourceKey]*unstructured.Unstructured),
}
ctrl := newFakeController(&data, nil)
- sources := make([]v1alpha1.ApplicationSource, 0)
+ sources := make([]argoappv1.ApplicationSource, 0)
sources = append(sources, app.Spec.GetSource())
revisions := make([]string, 0)
revisions = append(revisions, "")
@@ -1802,24 +1839,3 @@ func TestCompareAppStateRevisionUpdatedWithHelmSource(t *testing.T) {
assert.NotNil(t, compRes.syncStatus)
assert.True(t, compRes.revisionUpdated)
}
-
-func Test_normalizeClusterScopeTracking(t *testing.T) {
- obj := kube.MustToUnstructured(&rbacv1.ClusterRole{
- ObjectMeta: metav1.ObjectMeta{
- Name: "test",
- Namespace: "test",
- },
- })
- c := cachemocks.ClusterCache{}
- c.On("IsNamespaced", mock.Anything).Return(false, nil)
- var called bool
- err := normalizeClusterScopeTracking([]*unstructured.Unstructured{obj}, &c, func(u *unstructured.Unstructured) error {
- // We expect that the normalization function will call this callback with an obj that has had the namespace set
- // to empty.
- called = true
- assert.Empty(t, u.GetNamespace())
- return nil
- })
- require.NoError(t, err)
- require.True(t, called, "normalization function should have called the callback function")
-}
diff --git a/controller/sync.go b/controller/sync.go
index c1bacdafb9..9aed51682c 100644
--- a/controller/sync.go
+++ b/controller/sync.go
@@ -2,7 +2,7 @@ package controller
import (
"context"
- stderrors "errors"
+ goerrors "errors"
"fmt"
"os"
"strconv"
@@ -12,7 +12,7 @@ import (
"k8s.io/apimachinery/pkg/util/strategicpatch"
- cdcommon "github.com/argoproj/argo-cd/v3/common"
+ cdcommon "github.com/argoproj/argo-cd/v2/common"
gitopsDiff "github.com/argoproj/gitops-engine/pkg/diff"
"github.com/argoproj/gitops-engine/pkg/sync"
@@ -20,7 +20,7 @@ import (
"github.com/argoproj/gitops-engine/pkg/utils/kube"
jsonpatch "github.com/evanphx/json-patch"
log "github.com/sirupsen/logrus"
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+ v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/util/managedfields"
@@ -28,20 +28,19 @@ import (
"k8s.io/client-go/rest"
"k8s.io/kubectl/pkg/util/openapi"
- "github.com/argoproj/argo-cd/v3/controller/metrics"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- listersv1alpha1 "github.com/argoproj/argo-cd/v3/pkg/client/listers/application/v1alpha1"
- applog "github.com/argoproj/argo-cd/v3/util/app/log"
- "github.com/argoproj/argo-cd/v3/util/argo"
- "github.com/argoproj/argo-cd/v3/util/argo/diff"
- "github.com/argoproj/argo-cd/v3/util/glob"
- kubeutil "github.com/argoproj/argo-cd/v3/util/kube"
- logutils "github.com/argoproj/argo-cd/v3/util/log"
- "github.com/argoproj/argo-cd/v3/util/lua"
- "github.com/argoproj/argo-cd/v3/util/rand"
+ "github.com/argoproj/argo-cd/v2/controller/metrics"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+ listersv1alpha1 "github.com/argoproj/argo-cd/v2/pkg/client/listers/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/util/argo"
+ "github.com/argoproj/argo-cd/v2/util/argo/diff"
+ "github.com/argoproj/argo-cd/v2/util/glob"
+ kubeutil "github.com/argoproj/argo-cd/v2/util/kube"
+ logutils "github.com/argoproj/argo-cd/v2/util/log"
+ "github.com/argoproj/argo-cd/v2/util/lua"
+ "github.com/argoproj/argo-cd/v2/util/rand"
)
-var syncIdPrefix uint64
+var syncIdPrefix uint64 = 0
const (
// EnvVarSyncWaveDelay is an environment variable which controls the delay in seconds between
@@ -53,7 +52,7 @@ const (
serviceAccountDisallowedCharSet = "!*[]{}\\/"
)
-func (m *appStateManager) getOpenAPISchema(server *v1alpha1.Cluster) (openapi.Resources, error) {
+func (m *appStateManager) getOpenAPISchema(server string) (openapi.Resources, error) {
cluster, err := m.liveStateCache.GetClusterCache(server)
if err != nil {
return nil, err
@@ -61,7 +60,7 @@ func (m *appStateManager) getOpenAPISchema(server *v1alpha1.Cluster) (openapi.Re
return cluster.GetOpenAPISchema(), nil
}
-func (m *appStateManager) getGVKParser(server *v1alpha1.Cluster) (*managedfields.GvkParser, error) {
+func (m *appStateManager) getGVKParser(server string) (*managedfields.GvkParser, error) {
cluster, err := m.liveStateCache.GetClusterCache(server)
if err != nil {
return nil, err
@@ -73,12 +72,17 @@ func (m *appStateManager) getGVKParser(server *v1alpha1.Cluster) (*managedfields
// interface that provides functionality to dry run apply kubernetes resources. Returns a
// cleanup function that must be called to remove the generated kube config for this
// server.
-func (m *appStateManager) getServerSideDiffDryRunApplier(cluster *v1alpha1.Cluster) (gitopsDiff.KubeApplier, func(), error) {
- clusterCache, err := m.liveStateCache.GetClusterCache(cluster)
+func (m *appStateManager) getServerSideDiffDryRunApplier(server string) (gitopsDiff.KubeApplier, func(), error) {
+ clusterCache, err := m.liveStateCache.GetClusterCache(server)
if err != nil {
return nil, nil, fmt.Errorf("error getting cluster cache: %w", err)
}
+ cluster, err := m.db.GetCluster(context.Background(), server)
+ if err != nil {
+ return nil, nil, fmt.Errorf("error getting cluster: %w", err)
+ }
+
rawConfig, err := cluster.RawRestConfig()
if err != nil {
return nil, nil, fmt.Errorf("error getting cluster REST config: %w", err)
@@ -110,15 +114,6 @@ func (m *appStateManager) SyncAppState(app *v1alpha1.Application, state *v1alpha
}
syncOp = *state.Operation.Sync
- // validates if it should fail the sync if it finds shared resources
- hasSharedResource, sharedResourceMessage := hasSharedResourceCondition(app)
- if syncOp.SyncOptions.HasOption("FailOnSharedResource=true") &&
- hasSharedResource {
- state.Phase = common.OperationFailed
- state.Message = "Shared resource found: " + sharedResourceMessage
- return
- }
-
isMultiSourceRevision := app.Spec.HasMultipleSources()
rollback := len(syncOp.Sources) > 0 || syncOp.Source != nil
if rollback {
@@ -172,7 +167,7 @@ func (m *appStateManager) SyncAppState(app *v1alpha1.Application, state *v1alpha
}
}
- proj, err := argo.GetAppProject(context.TODO(), app, listersv1alpha1.NewAppProjectLister(m.projInformer.GetIndexer()), m.namespace, m.settingsMgr, m.db)
+ proj, err := argo.GetAppProject(app, listersv1alpha1.NewAppProjectLister(m.projInformer.GetIndexer()), m.namespace, m.settingsMgr, m.db, context.TODO())
if err != nil {
state.Phase = common.OperationError
state.Message = fmt.Sprintf("Failed to load application project: %v", err)
@@ -198,7 +193,7 @@ func (m *appStateManager) SyncAppState(app *v1alpha1.Application, state *v1alpha
// ignore error if CompareStateRepoError, this shouldn't happen as noRevisionCache is true
compareResult, err := m.CompareAppState(app, proj, revisions, sources, false, true, syncOp.Manifests, isMultiSourceRevision, rollback)
- if err != nil && !stderrors.Is(err, ErrCompareStateRepo) {
+ if err != nil && !goerrors.Is(err, CompareStateRepoError) {
state.Phase = common.OperationError
state.Message = err.Error()
return
@@ -209,6 +204,15 @@ func (m *appStateManager) SyncAppState(app *v1alpha1.Application, state *v1alpha
syncRes.Revision = compareResult.syncStatus.Revision
syncRes.Revisions = compareResult.syncStatus.Revisions
+ // validates if it should fail the sync if it finds shared resources
+ hasSharedResource, sharedResourceMessage := hasSharedResourceCondition(app)
+ if syncOp.SyncOptions.HasOption("FailOnSharedResource=true") &&
+ hasSharedResource {
+ state.Phase = common.OperationFailed
+ state.Message = fmt.Sprintf("Shared resource found: %s", sharedResourceMessage)
+ return
+ }
+
// If there are any comparison or spec errors error conditions do not perform the operation
if errConditions := app.Status.GetConditions(map[v1alpha1.ApplicationConditionType]bool{
v1alpha1.ApplicationConditionComparisonError: true,
@@ -219,21 +223,21 @@ func (m *appStateManager) SyncAppState(app *v1alpha1.Application, state *v1alpha
return
}
- destCluster, err := argo.GetDestinationCluster(context.Background(), app.Spec.Destination, m.db)
- if err != nil {
- state.Phase = common.OperationError
- state.Message = fmt.Sprintf("Failed to get destination cluster: %v", err)
- return
- }
-
- rawConfig, err := destCluster.RawRestConfig()
+ clst, err := m.db.GetCluster(context.Background(), app.Spec.Destination.Server)
if err != nil {
state.Phase = common.OperationError
state.Message = err.Error()
return
}
- clusterRESTConfig, err := destCluster.RESTConfig()
+ rawConfig, err := clst.RawRestConfig()
+ if err != nil {
+ state.Phase = common.OperationError
+ state.Message = err.Error()
+ return
+ }
+
+ clusterRESTConfig, err := clst.RESTConfig()
if err != nil {
state.Phase = common.OperationError
state.Message = err.Error()
@@ -257,11 +261,11 @@ func (m *appStateManager) SyncAppState(app *v1alpha1.Application, state *v1alpha
}
syncId := fmt.Sprintf("%05d-%s", syncIdPrefix, randSuffix)
- logEntry := log.WithFields(applog.GetAppLogFields(app)).WithField("syncId", syncId)
- initialResourcesRes := make([]common.ResourceSyncResult, len(syncRes.Resources))
+ logEntry := log.WithFields(log.Fields{"application": app.QualifiedName(), "syncId": syncId})
+ initialResourcesRes := make([]common.ResourceSyncResult, 0)
for i, res := range syncRes.Resources {
key := kube.ResourceKey{Group: res.Group, Kind: res.Kind, Namespace: res.Namespace, Name: res.Name}
- initialResourcesRes[i] = common.ResourceSyncResult{
+ initialResourcesRes = append(initialResourcesRes, common.ResourceSyncResult{
ResourceKey: key,
Message: res.Message,
Status: res.Status,
@@ -270,20 +274,20 @@ func (m *appStateManager) SyncAppState(app *v1alpha1.Application, state *v1alpha
SyncPhase: res.SyncPhase,
Version: res.Version,
Order: i + 1,
- }
+ })
}
- prunePropagationPolicy := metav1.DeletePropagationForeground
+ prunePropagationPolicy := v1.DeletePropagationForeground
switch {
case syncOp.SyncOptions.HasOption("PrunePropagationPolicy=background"):
- prunePropagationPolicy = metav1.DeletePropagationBackground
+ prunePropagationPolicy = v1.DeletePropagationBackground
case syncOp.SyncOptions.HasOption("PrunePropagationPolicy=foreground"):
- prunePropagationPolicy = metav1.DeletePropagationForeground
+ prunePropagationPolicy = v1.DeletePropagationForeground
case syncOp.SyncOptions.HasOption("PrunePropagationPolicy=orphan"):
- prunePropagationPolicy = metav1.DeletePropagationOrphan
+ prunePropagationPolicy = v1.DeletePropagationOrphan
}
- openAPISchema, err := m.getOpenAPISchema(destCluster)
+ openAPISchema, err := m.getOpenAPISchema(clst.Server)
if err != nil {
state.Phase = common.OperationError
state.Message = fmt.Sprintf("failed to load openAPISchema: %v", err)
@@ -305,16 +309,17 @@ 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)
return
}
- trackingMethod, err := m.settingsMgr.GetTrackingMethod()
- if err != nil {
- log.Errorf("Could not get trackingMethod: %v", err)
- return
- }
+ trackingMethod := argo.GetTrackingMethod(m.settingsMgr)
impersonationEnabled, err := m.settingsMgr.IsImpersonationEnabled()
if err != nil {
@@ -341,12 +346,12 @@ func (m *appStateManager) SyncAppState(app *v1alpha1.Application, state *v1alpha
opts := []sync.SyncOpt{
sync.WithLogr(logutils.NewLogrusLogger(logEntry)),
sync.WithHealthOverride(lua.ResourceHealthOverrides(resourceOverrides)),
- sync.WithPermissionValidator(func(un *unstructured.Unstructured, res *metav1.APIResource) error {
+ sync.WithPermissionValidator(func(un *unstructured.Unstructured, res *v1.APIResource) error {
if !proj.IsGroupKindPermitted(un.GroupVersionKind().GroupKind(), res.Namespaced) {
return fmt.Errorf("resource %s:%s is not permitted in project %s", un.GroupVersionKind().Group, un.GroupVersionKind().Kind, proj.Name)
}
if res.Namespaced {
- permitted, err := proj.IsDestinationPermitted(destCluster, un.GetNamespace(), func(project string) ([]*v1alpha1.Cluster, error) {
+ permitted, err := proj.IsDestinationPermitted(v1alpha1.ApplicationDestination{Namespace: un.GetNamespace(), Server: app.Spec.Destination.Server, Name: app.Spec.Destination.Name}, func(project string) ([]*v1alpha1.Cluster, error) {
return m.db.GetProjectClusters(context.TODO(), project)
})
if err != nil {
@@ -365,7 +370,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(), v1alpha1.TrackingMethod(trackingMethod), installationID)
+ m.isSelfReferencedObj(live, target, app.GetName(), appLabelKey, trackingMethod, installationID)
}),
sync.WithManifestValidation(!syncOp.SyncOptions.HasOption(common.SyncOptionsDisableValidation)),
sync.WithSyncWaveHook(delayBetweenSyncWaves),
@@ -376,7 +381,6 @@ func (m *appStateManager) SyncAppState(app *v1alpha1.Application, state *v1alpha
sync.WithServerSideApply(syncOp.SyncOptions.HasOption(common.SyncOptionServerSideApply)),
sync.WithServerSideApplyManager(cdcommon.ArgoCDSSAManager),
sync.WithPruneConfirmed(app.IsDeletionConfirmed(state.StartedAt.Time)),
- sync.WithSkipDryRunOnMissingResource(syncOp.SyncOptions.HasOption(common.SyncOptionSkipDryRunOnMissingResource)),
}
if syncOp.SyncOptions.HasOption("CreateNamespace=true") {
@@ -420,9 +424,9 @@ func (m *appStateManager) SyncAppState(app *v1alpha1.Application, state *v1alpha
for _, res := range resState {
augmentedMsg, err := argo.AugmentSyncMsg(res, func() ([]kube.APIResourceInfo, error) {
if apiVersion == nil {
- _, apiVersion, err = m.liveStateCache.GetVersionsInfo(destCluster)
+ _, apiVersion, err = m.liveStateCache.GetVersionsInfo(app.Spec.Destination.Server)
if err != nil {
- return nil, fmt.Errorf("failed to get version info from the target cluster %q", destCluster.Server)
+ return nil, fmt.Errorf("failed to get version info from the target cluster %q", app.Spec.Destination.Server)
}
}
return apiVersion, nil
@@ -527,7 +531,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 any) (*unstructured.Unstructured, error) {
+func applyMergePatch(obj *unstructured.Unstructured, patch []byte, versionedObject interface{}) (*unstructured.Unstructured, error) {
originalJSON, err := obj.MarshalJSON()
if err != nil {
return nil, err
@@ -570,7 +574,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(_ common.SyncPhase, _ int, finalWave bool) error {
+func delayBetweenSyncWaves(phase common.SyncPhase, wave int, finalWave bool) error {
if !finalWave {
delaySec := 2
if delaySecStr := os.Getenv(EnvVarSyncWaveDelay); delaySecStr != "" {
@@ -623,10 +627,11 @@ func deriveServiceAccountToImpersonate(project *v1alpha1.AppProject, application
return "", fmt.Errorf("default service account contains invalid chars '%s'", item.DefaultServiceAccount)
} else if strings.Contains(item.DefaultServiceAccount, ":") {
// service account is specified along with its namespace.
- return "system:serviceaccount:" + item.DefaultServiceAccount, nil
+ return fmt.Sprintf("system:serviceaccount:%s", 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/controller/sync_namespace.go b/controller/sync_namespace.go
index 2acf31654c..43e0dc6170 100644
--- a/controller/sync_namespace.go
+++ b/controller/sync_namespace.go
@@ -4,7 +4,7 @@ import (
gitopscommon "github.com/argoproj/gitops-engine/pkg/sync/common"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
)
// syncNamespace determine if Argo CD should create and/or manage the namespace
diff --git a/controller/sync_namespace_test.go b/controller/sync_namespace_test.go
index f8b045cbc5..0124d99532 100644
--- a/controller/sync_namespace_test.go
+++ b/controller/sync_namespace_test.go
@@ -8,7 +8,7 @@ import (
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/types"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
)
func createFakeNamespace(uid string, resourceVersion string, labels map[string]string, annotations map[string]string) *unstructured.Unstructured {
diff --git a/controller/sync_test.go b/controller/sync_test.go
index 135b57f356..b171fb8061 100644
--- a/controller/sync_test.go
+++ b/controller/sync_test.go
@@ -1,6 +1,7 @@
package controller
import (
+ "context"
"strconv"
"testing"
@@ -10,16 +11,17 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
corev1 "k8s.io/api/core/v1"
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+ v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
- "github.com/argoproj/argo-cd/v3/controller/testdata"
- "github.com/argoproj/argo-cd/v3/pkg/apis/application/v1alpha1"
- "github.com/argoproj/argo-cd/v3/reposerver/apiclient"
- "github.com/argoproj/argo-cd/v3/test"
- "github.com/argoproj/argo-cd/v3/util/argo/diff"
- "github.com/argoproj/argo-cd/v3/util/argo/normalizers"
+ argocommon "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"
+ "github.com/argoproj/argo-cd/v2/reposerver/apiclient"
+ "github.com/argoproj/argo-cd/v2/test"
+ "github.com/argoproj/argo-cd/v2/util/argo/diff"
+ "github.com/argoproj/argo-cd/v2/util/argo/normalizers"
)
func TestPersistRevisionHistory(t *testing.T) {
@@ -28,7 +30,7 @@ func TestPersistRevisionHistory(t *testing.T) {
app.Status.History = nil
defaultProject := &v1alpha1.AppProject{
- ObjectMeta: metav1.ObjectMeta{
+ ObjectMeta: v1.ObjectMeta{
Namespace: test.FakeArgoCDNamespace,
Name: "default",
},
@@ -53,7 +55,7 @@ func TestPersistRevisionHistory(t *testing.T) {
// Ensure we record spec.source into sync result
assert.Equal(t, app.Spec.GetSource(), opState.SyncResult.Source)
- updatedApp, err := ctrl.applicationClientset.ArgoprojV1alpha1().Applications(app.Namespace).Get(t.Context(), app.Name, metav1.GetOptions{})
+ updatedApp, err := ctrl.applicationClientset.ArgoprojV1alpha1().Applications(app.Namespace).Get(context.Background(), app.Name, v1.GetOptions{})
require.NoError(t, err)
require.Len(t, updatedApp.Status.History, 1)
assert.Equal(t, app.Spec.GetSource(), updatedApp.Status.History[0].Source)
@@ -74,7 +76,7 @@ func TestPersistManagedNamespaceMetadataState(t *testing.T) {
}
defaultProject := &v1alpha1.AppProject{
- ObjectMeta: metav1.ObjectMeta{
+ ObjectMeta: v1.ObjectMeta{
Namespace: test.FakeArgoCDNamespace,
Name: "default",
},
@@ -105,7 +107,7 @@ func TestPersistRevisionHistoryRollback(t *testing.T) {
app.Status.OperationState = nil
app.Status.History = nil
defaultProject := &v1alpha1.AppProject{
- ObjectMeta: metav1.ObjectMeta{
+ ObjectMeta: v1.ObjectMeta{
Namespace: test.FakeArgoCDNamespace,
Name: "default",
},
@@ -142,7 +144,7 @@ func TestPersistRevisionHistoryRollback(t *testing.T) {
// Ensure we record opState's source into sync result
assert.Equal(t, source, opState.SyncResult.Source)
- updatedApp, err := ctrl.applicationClientset.ArgoprojV1alpha1().Applications(app.Namespace).Get(t.Context(), app.Name, metav1.GetOptions{})
+ updatedApp, err := ctrl.applicationClientset.ArgoprojV1alpha1().Applications(app.Namespace).Get(context.Background(), app.Name, v1.GetOptions{})
require.NoError(t, err)
assert.Len(t, updatedApp.Status.History, 1)
assert.Equal(t, source, updatedApp.Status.History[0].Source)
@@ -155,7 +157,7 @@ func TestSyncComparisonError(t *testing.T) {
app.Status.History = nil
defaultProject := &v1alpha1.AppProject{
- ObjectMeta: metav1.ObjectMeta{
+ ObjectMeta: v1.ObjectMeta{
Namespace: test.FakeArgoCDNamespace,
Name: "default",
},
@@ -189,24 +191,36 @@ func TestSyncComparisonError(t *testing.T) {
}
func TestAppStateManager_SyncAppState(t *testing.T) {
+ t.Parallel()
+
type fixture struct {
- project *v1alpha1.AppProject
application *v1alpha1.Application
+ project *v1alpha1.AppProject
controller *ApplicationController
}
- setup := func() *fixture {
+ setup := func(liveObjects map[kube.ResourceKey]*unstructured.Unstructured) *fixture {
app := newFakeApp()
app.Status.OperationState = nil
app.Status.History = nil
+ if liveObjects == nil {
+ liveObjects = make(map[kube.ResourceKey]*unstructured.Unstructured)
+ }
+
project := &v1alpha1.AppProject{
- ObjectMeta: metav1.ObjectMeta{
+ ObjectMeta: v1.ObjectMeta{
Namespace: test.FakeArgoCDNamespace,
Name: "default",
},
Spec: v1alpha1.AppProjectSpec{
SignatureKeys: []v1alpha1.SignatureKey{{KeyID: "test"}},
+ Destinations: []v1alpha1.ApplicationDestination{
+ {
+ Namespace: "*",
+ Server: "*",
+ },
+ },
},
}
data := fakeData{
@@ -217,13 +231,13 @@ func TestAppStateManager_SyncAppState(t *testing.T) {
Server: test.FakeClusterURL,
Revision: "abc123",
},
- managedLiveObjs: make(map[kube.ResourceKey]*unstructured.Unstructured),
+ managedLiveObjs: liveObjects,
}
ctrl := newFakeController(&data, nil)
return &fixture{
- project: project,
application: app,
+ project: project,
controller: ctrl,
}
}
@@ -231,13 +245,23 @@ func TestAppStateManager_SyncAppState(t *testing.T) {
t.Run("will fail the sync if finds shared resources", func(t *testing.T) {
// given
t.Parallel()
- f := setup()
- syncErrorMsg := "deployment already applied by another application"
- condition := v1alpha1.ApplicationCondition{
- Type: v1alpha1.ApplicationConditionSharedResourceWarning,
- Message: syncErrorMsg,
- }
- f.application.Status.Conditions = append(f.application.Status.Conditions, condition)
+
+ sharedObject := kube.MustToUnstructured(&corev1.ConfigMap{
+ TypeMeta: v1.TypeMeta{
+ APIVersion: "v1",
+ Kind: "ConfigMap",
+ },
+ ObjectMeta: v1.ObjectMeta{
+ Name: "configmap1",
+ Namespace: "default",
+ Labels: map[string]string{
+ argocommon.LabelKeyAppInstance: "another-app",
+ },
+ },
+ })
+ liveObjects := make(map[kube.ResourceKey]*unstructured.Unstructured)
+ liveObjects[kube.GetResourceKey(sharedObject)] = sharedObject
+ f := setup(liveObjects)
// Sync with source unspecified
opState := &v1alpha1.OperationState{Operation: v1alpha1.Operation{
@@ -252,7 +276,7 @@ func TestAppStateManager_SyncAppState(t *testing.T) {
// then
assert.Equal(t, common.OperationFailed, opState.Phase)
- assert.Contains(t, opState.Message, syncErrorMsg)
+ assert.Contains(t, opState.Message, "ConfigMap/configmap1 is part of applications fake-argocd-ns/my-app and another-app")
})
}
@@ -269,7 +293,7 @@ func TestSyncWindowDeniesSync(t *testing.T) {
app.Status.History = nil
project := &v1alpha1.AppProject{
- ObjectMeta: metav1.ObjectMeta{
+ ObjectMeta: v1.ObjectMeta{
Namespace: test.FakeArgoCDNamespace,
Name: "default",
},
@@ -463,7 +487,7 @@ func TestNormalizeTargetResourcesWithList(t *testing.T) {
type fixture struct {
comparisonResult *comparisonResult
}
- setupHTTPProxy := func(t *testing.T, ignores []v1alpha1.ResourceIgnoreDifferences) *fixture {
+ setupHttpProxy := func(t *testing.T, ignores []v1alpha1.ResourceIgnoreDifferences) *fixture {
t.Helper()
dc, err := diff.NewDiffConfigBuilder().
WithDiffSettings(ignores, nil, true, normalizers.IgnoreNormalizerOpts{}).
@@ -493,7 +517,7 @@ func TestNormalizeTargetResourcesWithList(t *testing.T) {
// JSONPointers: []string{"/spec/routes"},
},
}
- f := setupHTTPProxy(t, ignores)
+ f := setupHttpProxy(t, ignores)
target := test.YamlToUnstructured(testdata.TargetHTTPProxy)
f.comparisonResult.reconciliationResult.Target = []*unstructured.Unstructured{target}
@@ -507,19 +531,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, []any{"spec", "routes", 0, "rateLimitPolicy", "global", "descriptors"}), 1)
+ require.Len(t, dig[[]any](f.comparisonResult.reconciliationResult.Live[0].Object, []interface{}{"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, []any{"spec", "routes", 0, "rateLimitPolicy", "global", "descriptors", 0, "entries", 0, "requestHeader", "headerName"}))
+ 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"}))
// target has 2 entries
- require.Len(t, dig[[]any](f.comparisonResult.reconciliationResult.Target[0].Object, []any{"spec", "routes", 0, "rateLimitPolicy", "global", "descriptors", 0, "entries"}), 2)
+ require.Len(t, dig[[]any](f.comparisonResult.reconciliationResult.Target[0].Object, []interface{}{"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, []any{"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, []interface{}{"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, []any{"spec", "routes", 0, "rateLimitPolicy", "global", "descriptors"}), 1)
+ require.Len(t, dig[[]any](patchedTargets[0].Object, []interface{}{"spec", "routes", 0, "rateLimitPolicy", "global", "descriptors"}), 1)
// and it should NOT equal an empty object
- require.Len(t, dig[any](patchedTargets[0].Object, []any{"spec", "routes", 0, "rateLimitPolicy", "global", "descriptors", 0, "entries", 0}), 1)
+ require.Len(t, dig[any](patchedTargets[0].Object, []interface{}{"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
@@ -530,7 +554,7 @@ func TestNormalizeTargetResourcesWithList(t *testing.T) {
JQPathExpressions: []string{".spec.template.spec.containers[].env[] | select(.name == \"SOME_ENV_VAR\")"},
},
}
- f := setupHTTPProxy(t, ignores)
+ f := setupHttpProxy(t, ignores)
live := test.YamlToUnstructured(testdata.LiveDeploymentEnvVarsYaml)
target := test.YamlToUnstructured(testdata.TargetDeploymentEnvVarsYaml)
f.comparisonResult.reconciliationResult.Live = []*unstructured.Unstructured{live}
@@ -547,10 +571,10 @@ func TestNormalizeTargetResourcesWithList(t *testing.T) {
require.True(t, ok)
assert.Len(t, containers, 1)
- ports := containers[0].(map[string]any)["ports"].([]any)
+ ports := containers[0].(map[string]interface{})["ports"].([]interface{})
assert.Len(t, ports, 1)
- env := containers[0].(map[string]any)["env"].([]any)
+ env := containers[0].(map[string]interface{})["env"].([]interface{})
assert.Len(t, env, 3)
first := env[0]
@@ -558,14 +582,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]any)["name"])
- assert.Equal(t, "some_value", first.(map[string]any)["value"])
+ 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_OTHER_ENV_VAR", second.(map[string]any)["name"])
- assert.Equal(t, "some_other_value", second.(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, "YET_ANOTHER_ENV_VAR", third.(map[string]any)["name"])
- assert.Equal(t, "yet_another_value", third.(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"])
})
t.Run("ignore-deployment-image-replicas-changes-additive", func(t *testing.T) {
@@ -582,7 +606,7 @@ func TestNormalizeTargetResourcesWithList(t *testing.T) {
JQPathExpressions: []string{".spec.template.spec.containers[].image"},
},
}
- f := setupHTTPProxy(t, ignores)
+ f := setupHttpProxy(t, ignores)
live := test.YamlToUnstructured(testdata.MinimalImageReplicaDeploymentYaml)
target := test.YamlToUnstructured(testdata.AdditionalImageReplicaDeploymentYaml)
f.comparisonResult.reconciliationResult.Live = []*unstructured.Unstructured{live}
@@ -597,7 +621,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]any)
+ labels, ok := metadata["labels"].(map[string]interface{})
require.True(t, ok)
assert.Len(t, labels, 2)
assert.Equal(t, "web", labels["appProcess"])
@@ -608,29 +632,29 @@ func TestNormalizeTargetResourcesWithList(t *testing.T) {
assert.Equal(t, int64(1), spec["replicas"])
- template, ok := spec["template"].(map[string]any)
+ template, ok := spec["template"].(map[string]interface{})
require.True(t, ok)
- tMetadata, ok := template["metadata"].(map[string]any)
+ tMetadata, ok := template["metadata"].(map[string]interface{})
require.True(t, ok)
- tLabels, ok := tMetadata["labels"].(map[string]any)
+ tLabels, ok := tMetadata["labels"].(map[string]interface{})
require.True(t, ok)
assert.Len(t, tLabels, 2)
assert.Equal(t, "web", tLabels["appProcess"])
- tSpec, ok := template["spec"].(map[string]any)
+ tSpec, ok := template["spec"].(map[string]interface{})
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]any)
+ first := containers[0].(map[string]interface{})
assert.Equal(t, "alpine:3", first["image"])
- resources, ok := first["resources"].(map[string]any)
+ resources, ok := first["resources"].(map[string]interface{})
require.True(t, ok)
- requests, ok := resources["requests"].(map[string]any)
+ requests, ok := resources["requests"].(map[string]interface{})
require.True(t, ok)
assert.Equal(t, "400m", requests["cpu"])
@@ -639,7 +663,7 @@ func TestNormalizeTargetResourcesWithList(t *testing.T) {
require.True(t, ok)
assert.Len(t, env, 1)
- env0 := env[0].(map[string]any)
+ env0 := env[0].(map[string]interface{})
assert.Equal(t, "EV", env0["name"])
assert.Equal(t, "here", env0["value"])
})
@@ -653,7 +677,7 @@ func TestDeriveServiceAccountMatchingNamespaces(t *testing.T) {
setup := func(destinationServiceAccounts []v1alpha1.ApplicationDestinationServiceAccount, destinationNamespace, destinationServerURL, applicationNamespace string) *fixture {
project := &v1alpha1.AppProject{
- ObjectMeta: metav1.ObjectMeta{
+ ObjectMeta: v1.ObjectMeta{
Namespace: "argocd-ns",
Name: "testProj",
},
@@ -662,7 +686,7 @@ func TestDeriveServiceAccountMatchingNamespaces(t *testing.T) {
},
}
app := &v1alpha1.Application{
- ObjectMeta: metav1.ObjectMeta{
+ ObjectMeta: v1.ObjectMeta{
Namespace: applicationNamespace,
Name: "testApp",
},
@@ -999,7 +1023,7 @@ func TestDeriveServiceAccountMatchingServers(t *testing.T) {
setup := func(destinationServiceAccounts []v1alpha1.ApplicationDestinationServiceAccount, destinationNamespace, destinationServerURL, applicationNamespace string) *fixture {
project := &v1alpha1.AppProject{
- ObjectMeta: metav1.ObjectMeta{
+ ObjectMeta: v1.ObjectMeta{
Namespace: "argocd-ns",
Name: "testProj",
},
@@ -1008,7 +1032,7 @@ func TestDeriveServiceAccountMatchingServers(t *testing.T) {
},
}
app := &v1alpha1.Application{
- ObjectMeta: metav1.ObjectMeta{
+ ObjectMeta: v1.ObjectMeta{
Namespace: applicationNamespace,
Name: "testApp",
},
@@ -1278,7 +1302,7 @@ func TestSyncWithImpersonate(t *testing.T) {
app.Status.OperationState = nil
app.Status.History = nil
project := &v1alpha1.AppProject{
- ObjectMeta: metav1.ObjectMeta{
+ ObjectMeta: v1.ObjectMeta{
Namespace: test.FakeArgoCDNamespace,
Name: "default",
},
@@ -1296,7 +1320,7 @@ func TestSyncWithImpersonate(t *testing.T) {
additionalObjs := []runtime.Object{}
if serviceAccountName != "" {
syncServiceAccount := &corev1.ServiceAccount{
- ObjectMeta: metav1.ObjectMeta{
+ ObjectMeta: v1.ObjectMeta{
Name: serviceAccountName,
Namespace: test.FakeDestNamespace,
},
@@ -1410,15 +1434,15 @@ func TestSyncWithImpersonate(t *testing.T) {
})
}
-func dig[T any](obj any, path []any) T {
+func dig[T any](obj interface{}, path []interface{}) T {
i := obj
for _, segment := range path {
switch segment.(type) {
case int:
- i = i.([]any)[segment.(int)]
+ i = i.([]interface{})[segment.(int)]
case string:
- i = i.(map[string]any)[segment.(string)]
+ i = i.(map[string]interface{})[segment.(string)]
default:
panic("invalid path for object")
}
diff --git a/controller/testdata/diff-cache.yaml b/controller/testdata/diff-cache.yaml
index 18523c8595..41a1e8a4bb 100644
--- a/controller/testdata/diff-cache.yaml
+++ b/controller/testdata/diff-cache.yaml
@@ -51,7 +51,7 @@ spec:
- name: RELEASE_NAME
value: test-lla
- name: CHART_REPOSITORY
- value: oci://europe-west1-docker.pkg.dev/foo/charts
+ value: oci://europe-west1-docker.pkg.dev/platform-89be/charts
- name: CHART_NAME
value: velero
- name: PREVIEW
@@ -67,7 +67,7 @@ spec:
- name: HELM_ARGS
value: ""
name: cmp-helm-v2
- repoURL: https://github.com/foo/manifests-velero.git
+ repoURL: https://github.com/mirakl/manifests-velero.git
targetRevision: test-lla
syncPolicy:
retry:
@@ -98,7 +98,7 @@ status:
- name: RELEASE_NAME
value: test-lla
- name: CHART_REPOSITORY
- value: oci://europe-west1-docker.pkg.dev/foo/charts
+ value: oci://europe-west1-docker.pkg.dev/platform-89be/charts
- name: CHART_NAME
value: velero
- name: PREVIEW
@@ -114,7 +114,7 @@ status:
- name: HELM_ARGS
value: ""
name: cmp-helm-v2
- repoURL: https://github.com/foo/manifests-velero.git
+ repoURL: https://github.com/mirakl/manifests-velero.git
targetRevision: test-lla
- deployStartedAt: "2024-03-04T22:08:29Z"
deployedAt: "2024-03-04T22:08:30Z"
@@ -127,7 +127,7 @@ status:
- name: RELEASE_NAME
value: test-lla
- name: CHART_REPOSITORY
- value: oci://europe-west1-docker.pkg.dev/foo/charts
+ value: oci://europe-west1-docker.pkg.dev/platform-89be/charts
- name: CHART_NAME
value: velero
- name: PREVIEW
@@ -143,7 +143,7 @@ status:
- name: HELM_ARGS
value: ""
name: cmp-helm-v2
- repoURL: https://github.com/foo/manifests-velero.git
+ repoURL: https://github.com/mirakl/manifests-velero.git
targetRevision: test-lla
- deployStartedAt: "2024-03-04T22:09:16Z"
deployedAt: "2024-03-04T22:09:16Z"
@@ -156,7 +156,7 @@ status:
- name: RELEASE_NAME
value: test-lla
- name: CHART_REPOSITORY
- value: oci://europe-west1-docker.pkg.dev/foo/charts
+ value: oci://europe-west1-docker.pkg.dev/platform-89be/charts
- name: CHART_NAME
value: velero
- name: PREVIEW
@@ -172,7 +172,7 @@ status:
- name: HELM_ARGS
value: ""
name: cmp-helm-v2
- repoURL: https://github.com/foo/manifests-velero.git
+ repoURL: https://github.com/mirakl/manifests-velero.git
targetRevision: test-lla
- deployStartedAt: "2024-03-04T22:11:41Z"
deployedAt: "2024-03-04T22:11:41Z"
@@ -185,7 +185,7 @@ status:
- name: RELEASE_NAME
value: test-lla
- name: CHART_REPOSITORY
- value: oci://europe-west1-docker.pkg.dev/foo/charts
+ value: oci://europe-west1-docker.pkg.dev/platform-89be/charts
- name: CHART_NAME
value: velero
- name: PREVIEW
@@ -201,7 +201,7 @@ status:
- name: HELM_ARGS
value: ""
name: cmp-helm-v2
- repoURL: https://github.com/foo/manifests-velero.git
+ repoURL: https://github.com/mirakl/manifests-velero.git
targetRevision: test-lla
- deployStartedAt: "2024-03-04T22:50:55Z"
deployedAt: "2024-03-04T22:50:55Z"
@@ -214,7 +214,7 @@ status:
- name: RELEASE_NAME
value: test-lla
- name: CHART_REPOSITORY
- value: oci://europe-west1-docker.pkg.dev/foo/charts
+ value: oci://europe-west1-docker.pkg.dev/platform-89be/charts
- name: CHART_NAME
value: velero
- name: PREVIEW
@@ -230,7 +230,7 @@ status:
- name: HELM_ARGS
value: ""
name: cmp-helm-v2
- repoURL: https://github.com/foo/manifests-velero.git
+ repoURL: https://github.com/mirakl/manifests-velero.git
targetRevision: test-lla
- deployStartedAt: "2024-03-04T22:52:56Z"
deployedAt: "2024-03-04T22:52:56Z"
@@ -243,7 +243,7 @@ status:
- name: RELEASE_NAME
value: test-lla
- name: CHART_REPOSITORY
- value: oci://europe-west1-docker.pkg.dev/foo/charts
+ value: oci://europe-west1-docker.pkg.dev/platform-89be/charts
- name: CHART_NAME
value: velero
- name: PREVIEW
@@ -259,7 +259,7 @@ status:
- name: HELM_ARGS
value: ""
name: cmp-helm-v2
- repoURL: https://github.com/foo/manifests-velero.git
+ repoURL: https://github.com/mirakl/manifests-velero.git
targetRevision: test-lla
- deployStartedAt: "2024-03-04T22:56:15Z"
deployedAt: "2024-03-04T22:56:15Z"
@@ -272,7 +272,7 @@ status:
- name: RELEASE_NAME
value: test-lla
- name: CHART_REPOSITORY
- value: oci://europe-west1-docker.pkg.dev/foo/charts
+ value: oci://europe-west1-docker.pkg.dev/platform-89be/charts
- name: CHART_NAME
value: velero
- name: PREVIEW
@@ -288,7 +288,7 @@ status:
- name: HELM_ARGS
value: ""
name: cmp-helm-v2
- repoURL: https://github.com/foo/manifests-velero.git
+ repoURL: https://github.com/mirakl/manifests-velero.git
targetRevision: test-lla
- deployStartedAt: "2024-03-05T07:31:56Z"
deployedAt: "2024-03-05T07:31:57Z"
@@ -301,7 +301,7 @@ status:
- name: RELEASE_NAME
value: test-lla
- name: CHART_REPOSITORY
- value: oci://europe-west1-docker.pkg.dev/foo/charts
+ value: oci://europe-west1-docker.pkg.dev/platform-89be/charts
- name: CHART_NAME
value: velero
- name: PREVIEW
@@ -317,7 +317,7 @@ status:
- name: HELM_ARGS
value: ""
name: cmp-helm-v2
- repoURL: https://github.com/foo/manifests-velero.git
+ repoURL: https://github.com/mirakl/manifests-velero.git
targetRevision: test-lla
- deployStartedAt: "2024-03-05T07:32:44Z"
deployedAt: "2024-03-05T07:32:44Z"
@@ -330,7 +330,7 @@ status:
- name: RELEASE_NAME
value: test-lla
- name: CHART_REPOSITORY
- value: oci://europe-west1-docker.pkg.dev/foo/charts
+ value: oci://europe-west1-docker.pkg.dev/platform-89be/charts
- name: CHART_NAME
value: velero
- name: PREVIEW
@@ -346,7 +346,7 @@ status:
- name: HELM_ARGS
value: ""
name: cmp-helm-v2
- repoURL: https://github.com/foo/manifests-velero.git
+ repoURL: https://github.com/mirakl/manifests-velero.git
targetRevision: test-lla
- deployStartedAt: "2024-03-05T07:33:03Z"
deployedAt: "2024-03-05T07:33:04Z"
@@ -359,7 +359,7 @@ status:
- name: RELEASE_NAME
value: test-lla
- name: CHART_REPOSITORY
- value: oci://europe-west1-docker.pkg.dev/foo/charts
+ value: oci://europe-west1-docker.pkg.dev/platform-89be/charts
- name: CHART_NAME
value: velero
- name: PREVIEW
@@ -375,14 +375,14 @@ status:
- name: HELM_ARGS
value: ""
name: cmp-helm-v2
- repoURL: https://github.com/foo/manifests-velero.git
+ repoURL: https://github.com/mirakl/manifests-velero.git
targetRevision: test-lla
operationState:
finishedAt: "2024-03-05T07:33:04Z"
message: successfully synced (all tasks run)
operation:
initiatedBy:
- username: foo@example.com
+ username: laurent.lavaud@mirakl.com
retry:
backoff:
duration: 5s
@@ -425,7 +425,7 @@ status:
- name: RELEASE_NAME
value: test-lla
- name: CHART_REPOSITORY
- value: oci://europe-west1-docker.pkg.dev/foo/charts
+ value: oci://europe-west1-docker.pkg.dev/platform-89be/charts
- name: CHART_NAME
value: velero
- name: PREVIEW
@@ -441,7 +441,7 @@ status:
- name: HELM_ARGS
value: ""
name: cmp-helm-v2
- repoURL: https://github.com/foo/manifests-velero.git
+ repoURL: https://github.com/mirakl/manifests-velero.git
targetRevision: test-lla
reconciledAt: "2024-03-05T07:33:04Z"
resources:
@@ -476,7 +476,7 @@ status:
- name: RELEASE_NAME
value: test-lla
- name: CHART_REPOSITORY
- value: oci://europe-west1-docker.pkg.dev/foo/charts
+ value: oci://europe-west1-docker.pkg.dev/platform-89be/charts
- name: CHART_NAME
value: velero
- name: PREVIEW
@@ -492,7 +492,7 @@ status:
- name: HELM_ARGS
value: ""
name: cmp-helm-v2
- repoURL: https://github.com/foo/manifests-velero.git
+ repoURL: https://github.com/mirakl/manifests-velero.git
targetRevision: test-lla
revision: rev1
status: Synced
diff --git a/controller/testdata/live-deployment-env-vars.yaml b/controller/testdata/live-deployment-env-vars.yaml
index b72cfad3f8..c4d917b640 100644
--- a/controller/testdata/live-deployment-env-vars.yaml
+++ b/controller/testdata/live-deployment-env-vars.yaml
@@ -6,7 +6,7 @@ metadata:
deployment.kubernetes.io/revision: '9'
iksm-version: '2.0'
kubectl.kubernetes.io/last-applied-configuration: >
- {"apiVersion":"apps/v1","kind":"Deployment","metadata":{"annotations":{"argocd.argoproj.io/tracking-id":"guestbook:apps/Deployment:default/kustomize-guestbook-ui","iksm-version":"2.0"},"name":"kustomize-guestbook-ui","namespace":"default"},"spec":{"replicas":4,"revisionHistoryLimit":3,"selector":{"matchLabels":{"app":"guestbook-ui"}},"template":{"metadata":{"labels":{"app":"guestbook-ui"}},"spec":{"containers":[{"env":[{"name":"SOME_ENV_VAR","value":"some_value"}],"image":"quay.io/argoprojlabs/argocd-e2e-container:0.1","name":"guestbook-ui","ports":[{"containerPort":80}],"resources":{"requests":{"cpu":"50m","memory":"100Mi"}}}]}}}}
+ {"apiVersion":"apps/v1","kind":"Deployment","metadata":{"annotations":{"argocd.argoproj.io/tracking-id":"guestbook:apps/Deployment:default/kustomize-guestbook-ui","iksm-version":"2.0"},"name":"kustomize-guestbook-ui","namespace":"default"},"spec":{"replicas":4,"revisionHistoryLimit":3,"selector":{"matchLabels":{"app":"guestbook-ui"}},"template":{"metadata":{"labels":{"app":"guestbook-ui"}},"spec":{"containers":[{"env":[{"name":"SOME_ENV_VAR","value":"some_value"}],"image":"gcr.io/heptio-images/ks-guestbook-demo:0.1","name":"guestbook-ui","ports":[{"containerPort":80}],"resources":{"requests":{"cpu":"50m","memory":"100Mi"}}}]}}}}
creationTimestamp: '2022-01-05T15:45:21Z'
generation: 119
managedFields:
@@ -137,7 +137,7 @@ spec:
- env:
- name: SOME_ENV_VAR
value: some_value
- image: 'quay.io/argoprojlabs/argocd-e2e-container:0.1'
+ image: 'gcr.io/heptio-images/ks-guestbook-demo:0.1'
imagePullPolicy: IfNotPresent
name: guestbook-ui
ports:
diff --git a/controller/testdata/live-deployment.yaml b/controller/testdata/live-deployment.yaml
index 898dbfaade..731b5b7207 100644
--- a/controller/testdata/live-deployment.yaml
+++ b/controller/testdata/live-deployment.yaml
@@ -6,7 +6,7 @@ metadata:
deployment.kubernetes.io/revision: '9'
iksm-version: '2.0'
kubectl.kubernetes.io/last-applied-configuration: >
- {"apiVersion":"apps/v1","kind":"Deployment","metadata":{"annotations":{"argocd.argoproj.io/tracking-id":"guestbook:apps/Deployment:default/kustomize-guestbook-ui","iksm-version":"2.0"},"name":"kustomize-guestbook-ui","namespace":"default"},"spec":{"replicas":4,"revisionHistoryLimit":3,"selector":{"matchLabels":{"app":"guestbook-ui"}},"template":{"metadata":{"labels":{"app":"guestbook-ui"}},"spec":{"containers":[{"env":[{"name":"SOME_ENV_VAR","value":"some_value"}],"image":"quay.io/argoprojlabs/argocd-e2e-container:0.1","name":"guestbook-ui","ports":[{"containerPort":80}],"resources":{"requests":{"cpu":"50m","memory":"100Mi"}}}]}}}}
+ {"apiVersion":"apps/v1","kind":"Deployment","metadata":{"annotations":{"argocd.argoproj.io/tracking-id":"guestbook:apps/Deployment:default/kustomize-guestbook-ui","iksm-version":"2.0"},"name":"kustomize-guestbook-ui","namespace":"default"},"spec":{"replicas":4,"revisionHistoryLimit":3,"selector":{"matchLabels":{"app":"guestbook-ui"}},"template":{"metadata":{"labels":{"app":"guestbook-ui"}},"spec":{"containers":[{"env":[{"name":"SOME_ENV_VAR","value":"some_value"}],"image":"gcr.io/heptio-images/ks-guestbook-demo:0.1","name":"guestbook-ui","ports":[{"containerPort":80}],"resources":{"requests":{"cpu":"50m","memory":"100Mi"}}}]}}}}
creationTimestamp: '2022-01-05T15:45:21Z'
generation: 119
managedFields:
@@ -137,7 +137,7 @@ spec:
- env:
- name: SOME_ENV_VAR
value: some_value
- image: 'quay.io/argoprojlabs/argocd-e2e-container:0.1'
+ image: 'gcr.io/heptio-images/ks-guestbook-demo:0.1'
imagePullPolicy: IfNotPresent
name: guestbook-ui
ports:
diff --git a/controller/testdata/target-deployment-env-vars.yaml b/controller/testdata/target-deployment-env-vars.yaml
index b01a4ac77e..d4b55561ad 100644
--- a/controller/testdata/target-deployment-env-vars.yaml
+++ b/controller/testdata/target-deployment-env-vars.yaml
@@ -25,7 +25,7 @@ spec:
value: yet_another_value
- name: SOME_ENV_VAR
value: different_value!
- image: 'quay.io/argoprojlabs/argocd-e2e-container:0.1'
+ image: 'gcr.io/heptio-images/ks-guestbook-demo:0.1'
name: guestbook-ui
ports:
- containerPort: 80
diff --git a/controller/testdata/target-deployment-new-entries.yaml b/controller/testdata/target-deployment-new-entries.yaml
index 8cda879efe..b09ca1c9fb 100644
--- a/controller/testdata/target-deployment-new-entries.yaml
+++ b/controller/testdata/target-deployment-new-entries.yaml
@@ -19,7 +19,7 @@ spec:
spec:
containers:
- name: guestbook-ui
- image: 'quay.io/argoprojlabs/argocd-e2e-container:0.1'
+ image: 'gcr.io/heptio-images/ks-guestbook-demo:0.1'
env:
- name: SOME_ENV_VAR
value: some_value
diff --git a/controller/testdata/target-deployment.yaml b/controller/testdata/target-deployment.yaml
index 9e66f17cc7..111647f9ac 100644
--- a/controller/testdata/target-deployment.yaml
+++ b/controller/testdata/target-deployment.yaml
@@ -21,7 +21,7 @@ spec:
- env:
- name: SOME_ENV_VAR
value: some_value
- image: 'quay.io/argoprojlabs/argocd-e2e-container:0.1'
+ image: 'gcr.io/heptio-images/ks-guestbook-demo:0.1'
name: guestbook-ui
ports:
- containerPort: 80
diff --git a/controller/utils/log.go b/controller/utils/log.go
new file mode 100644
index 0000000000..3c5a244e73
--- /dev/null
+++ b/controller/utils/log.go
@@ -0,0 +1,17 @@
+package utils
+
+import (
+ "github.com/sirupsen/logrus"
+
+ "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
+)
+
+// GetAppLog returns a logrus entry with fields set for the given application.
+func GetAppLog(app *v1alpha1.Application) *logrus.Entry {
+ return logrus.WithFields(logrus.Fields{
+ "application": app.Name,
+ "app-namespace": app.Namespace,
+ "app-qualified-name": app.QualifiedName(),
+ "project": app.Spec.Project,
+ })
+}
diff --git a/docs/assets/identity-center-1.png b/docs/assets/identity-center-1.png
index 1e308dd461..0cd49528d9 100644
Binary files a/docs/assets/identity-center-1.png and b/docs/assets/identity-center-1.png differ
diff --git a/docs/assets/repo-add-azure-workload-identity.png b/docs/assets/repo-add-azure-workload-identity.png
deleted file mode 100755
index 3a844c0c68..0000000000
Binary files a/docs/assets/repo-add-azure-workload-identity.png and /dev/null differ
diff --git a/docs/assets/scale_resources_1.png b/docs/assets/scale_resources_1.png
deleted file mode 100644
index 73b7fb45a8..0000000000
Binary files a/docs/assets/scale_resources_1.png and /dev/null differ
diff --git a/docs/assets/scale_resources_2.png b/docs/assets/scale_resources_2.png
deleted file mode 100644
index e88d3aee6f..0000000000
Binary files a/docs/assets/scale_resources_2.png and /dev/null differ
diff --git a/docs/assets/scale_resources_3.png b/docs/assets/scale_resources_3.png
deleted file mode 100644
index 04f62e4a24..0000000000
Binary files a/docs/assets/scale_resources_3.png and /dev/null differ
diff --git a/docs/cli_installation.md b/docs/cli_installation.md
index e5d92ed1ed..5a314d4ce6 100644
--- a/docs/cli_installation.md
+++ b/docs/cli_installation.md
@@ -51,19 +51,9 @@ rm argocd-linux-amd64
You should now be able to run `argocd` commands.
-## Mac (Apple Silicon)
+## Mac (M1)
-### Install via Homebrew or Curl
-
-You can install the CLI using `Homebrew` or a `Curl` command:
-
-#### Homebrew
-
-```bash
-brew install argocd
-```
-
-#### Download With Curl
+### Download With Curl
You can view the latest version of Argo CD at the link above or run the following command to grab the version:
@@ -74,14 +64,44 @@ VERSION=$(curl --silent "https://api.github.com/repos/argoproj/argo-cd/releases/
Replace `VERSION` in the command below with the version of Argo CD you would like to download:
```bash
-curl -sSL -o argocd https://github.com/argoproj/argo-cd/releases/download/$VERSION/argocd-darwin-arm64
+curl -sSL -o argocd-darwin-arm64 https://github.com/argoproj/argo-cd/releases/download/$VERSION/argocd-darwin-arm64
```
Install the Argo CD CLI binary:
```bash
-sudo install -m 555 argocd /usr/local/bin/argocd
-rm argocd
+sudo install -m 555 argocd-darwin-arm64 /usr/local/bin/argocd
+rm argocd-darwin-arm64
+```
+
+
+## Mac
+
+### Homebrew
+
+```bash
+brew install argocd
+```
+
+### Download With Curl
+
+You can view the latest version of Argo CD at the link above or run the following command to grab the version:
+
+```bash
+VERSION=$(curl --silent "https://api.github.com/repos/argoproj/argo-cd/releases/latest" | grep '"tag_name"' | sed -E 's/.*"([^"]+)".*/\1/')
+```
+
+Replace `VERSION` in the command below with the version of Argo CD you would like to download:
+
+```bash
+curl -sSL -o argocd-darwin-amd64 https://github.com/argoproj/argo-cd/releases/download/$VERSION/argocd-darwin-amd64
+```
+
+Install the Argo CD CLI binary:
+
+```bash
+sudo install -m 555 argocd-darwin-amd64 /usr/local/bin/argocd
+rm argocd-darwin-amd64
```
After finishing either of the instructions above, you should now be able to run `argocd` commands.
diff --git a/docs/developer-guide/architecture/authz-authn.md b/docs/developer-guide/architecture/authz-authn.md
index 5359073ed7..921b744f2e 100644
--- a/docs/developer-guide/architecture/authz-authn.md
+++ b/docs/developer-guide/architecture/authz-authn.md
@@ -104,6 +104,6 @@ elements are described below with their respective numbers:
[3]: https://en.wikipedia.org/wiki/Representational_state_transfer
[4]: https://grpc.io/
[5]: https://casbin.org/
-[6]: https://go.dev/wiki/LearnServerProgramming#middleware
+[6]: https://github.com/golang/go/wiki/LearnServerProgramming#middleware
[7]: https://en.wikipedia.org/wiki/Role-based_access_control
[8]: https://pkg.go.dev/net/http#ServeMux
diff --git a/docs/developer-guide/contributors-quickstart.md b/docs/developer-guide/contributors-quickstart.md
index 3a9de03de8..5544742b7a 100644
--- a/docs/developer-guide/contributors-quickstart.md
+++ b/docs/developer-guide/contributors-quickstart.md
@@ -20,15 +20,15 @@ Before starting, ensure you have the following tools installed with the specifie
### Fork and Clone the Repository
-1. Fork the Argo CD repository to your personal GitHub Account
+1. Fork the Argo CD repository to your personal Github Account
2. Clone the forked repository:
```shell
+mkdir -p $GOPATH/src/github.com/argoproj/
+cd $GOPATH/src/github.com/argoproj/
git clone https://github.com/YOUR-USERNAME/argo-cd.git
```
-Please note that the local build process uses GOPATH and that path should not be used, unless the Argo CD repository was directly cloned in it.
-
3. Add the upstream remote for rebasing:
```shell
cd argo-cd
@@ -40,7 +40,7 @@ git remote add upstream https://github.com/argoproj/argo-cd.git
1. Install development tools:
```shell
make install-go-tools-local
-make install-codegen-tools-local
+make install-code-gen-tools-local
```
### Install Go
@@ -134,31 +134,15 @@ DOCKER=podman make start-local ARGOCD_GPG_ENABLED=false
## Common Make Targets
-Here are some frequently used make targets (all will run on your machine):
+Here are some frequently used make targets:
-### Local Toolchain Make Targets
-
-* `make build-local` - Build Argo CD binaries
-* `make test-local` - Run unit tests
-* `make codegen-local` - Re-generate auto generated Swagger and Protobuf (after changing API code)
-* `make lint-local` - Run linting
-* `make pre-commit-local` - Run pre-commit checks
-* `make start-e2e-local` - Start server for end-to-end tests
-* `make test-e2e-local` - Run end-to-end tests
-* `make serve-docs-local` - Serve documentation
-* `make start-local` - Start Argo CD
-
-### Virtualized Toolchain Make Targets
-
-* `make build` - Build Argo CD binaries
+* `make start-local` - Start Argo CD locally
* `make test` - Run unit tests
-* `make codegen` - Re-generate auto generated Swagger and Protobuf (after changing API code)
-* `make lint` - Run linting
-* `make pre-commit` - Run pre-commit checks
-* `make start-e2e` - Start server for end-to-end tests
* `make test-e2e` - Run end-to-end tests
-* `make serve-docs` - Serve documentation
-* `make start` - Start Argo CD
+* `make lint` - Run linting
+* `make serve-docs` - Serve documentation locally
+* `make pre-commit-local` - Run pre-commit checks locally
+* `make build` - Build Argo CD binaries
## Making Changes
diff --git a/docs/developer-guide/dependencies.md b/docs/developer-guide/dependencies.md
index e609a23e16..2a4c869825 100644
--- a/docs/developer-guide/dependencies.md
+++ b/docs/developer-guide/dependencies.md
@@ -47,7 +47,7 @@ If you make changes to the Argo UI component, and your Argo CD changes depend on
2. Also, prepare your Argo CD changes, but don't create the PR just yet.
3. **After** the Argo UI PR has been merged to master, then as part of your Argo CD changes:
- Run `yarn add git+https://github.com/argoproj/argo-ui.git` in the `ui/` directory, and then,
- - Check in the regenerated `yarn.lock` file as part of your Argo CD commit
+ - Check in the regenerated yarn.lock file as part of your Argo CD commit
4. Create the Argo CD PR when you are ready. The PR build and test checks should pass.
-If your Argo UI change is a 'stand-alone' fix, and you simply want Argo CD to pull in your change, then simply create an Argo CD PR with the `yarn.lock` file change.
+If your Argo UI change is a 'stand-alone' fix, and you simply want Argo CD to pull in your change, then simply create an Argo CD PR with the yarn.lock file change.
diff --git a/docs/developer-guide/extensions/proxy-extensions.md b/docs/developer-guide/extensions/proxy-extensions.md
index e47c25b081..cd41452fbc 100644
--- a/docs/developer-guide/extensions/proxy-extensions.md
+++ b/docs/developer-guide/extensions/proxy-extensions.md
@@ -1,8 +1,8 @@
# Proxy Extensions
-!!! warning "Beta Feature (Since 2.7.0)"
- This feature is in the [Beta](https://github.com/argoproj/argoproj/blob/main/community/feature-status.md#beta) stage.
- It is generally considered stable, but there may be unhandled edge cases.
+!!! warning "Alpha Feature (Since 2.7.0)"
+ This is an experimental, [alpha-quality](https://github.com/argoproj/argoproj/blob/main/community/feature-status.md#alpha)
+ feature. It may be removed in future releases or modified in backwards-incompatible ways.
## Overview
diff --git a/docs/developer-guide/release-process-and-cadence.md b/docs/developer-guide/release-process-and-cadence.md
index 415ac10ede..bda586a97e 100644
--- a/docs/developer-guide/release-process-and-cadence.md
+++ b/docs/developer-guide/release-process-and-cadence.md
@@ -17,7 +17,7 @@ These are the upcoming releases dates:
| v2.12 | Monday, Jun. 17, 2024 | Monday, Aug. 5, 2024 | [Ishita Sequeira](https://github.com/ishitasequeira) | [Pavel Kostohrys](https://github.com/pasha-codefresh) | [checklist](https://github.com/argoproj/argo-cd/issues/19063) |
| v2.13 | Monday, Sep. 16, 2024 | Monday, Nov. 4, 2024 | [Regina Voloshin](https://github.com/reggie-k) | [Pavel Kostohrys](https://github.com/pasha-codefresh) | [checklist](https://github.com/argoproj/argo-cd/issues/19513) |
| v2.14 | Monday, Dec. 16, 2024 | Monday, Feb. 3, 2025 | [Ryan Umstead](https://github.com/rumstead) | [Pavel Kostohrys](https://github.com/pasha-codefresh) | [checklist](https://github.com/argoproj/argo-cd/issues/20869) |
-| v3.0 | Monday, Mar. 17, 2025 | Tuesday, May 6, 2025 | [Regina Voloshin](https://github.com/reggie-k) | | [checklist](https://github.com/argoproj/argo-cd/issues/21735) |
+| v2.15 | Monday, Mar. 17, 2025 | Monday, May 5, 2025 | | | |
Actual release dates might differ from the plan by a few days.
@@ -88,4 +88,4 @@ These evaluations vary from dependency to dependencies.
Dependencies are also scheduled for removal if the project has been deprecated or if the project is no longer maintained.
CVEs in dependencies will be patched for all supported versions if the CVE is applicable and is assessed by Snyk to be
-of high or critical severity. Automation generates a [new Snyk scan weekly](../snyk/index.md).
+of high or critical severity. Automation generates a [new Snyk scan weekly](../snyk).
diff --git a/docs/developer-guide/releasing.md b/docs/developer-guide/releasing.md
index 4764539ee2..bb51ebfa8d 100644
--- a/docs/developer-guide/releasing.md
+++ b/docs/developer-guide/releasing.md
@@ -20,9 +20,8 @@ triggered. This will be automated in the very near future.
* Update `CHANGELOG.md` with changes for this release
* Commit & push changes to `CHANGELOG.md`
-* Update `goreleaser.yaml` with the updated blog post link in the `Release Notes Blog Post` section.
-**The `Init ArgoCD Release` workflow will perform the following steps:**
+**The `Init ARGOCD Release` workflow will perform the following steps:**
* Update `VERSION` file in the release branch
* Update manifests with image tags of the new version in the release branch
diff --git a/docs/developer-guide/running-locally.md b/docs/developer-guide/running-locally.md
index f1e6db9b88..25f4510e9e 100644
--- a/docs/developer-guide/running-locally.md
+++ b/docs/developer-guide/running-locally.md
@@ -123,7 +123,7 @@ $ goreman run status
[...]
```
-If some of the processes fail to start (not marked with `*`), check logs to see why they are not running.
+If not all critical processes run (marked with `*`), check logs to see why they terminated.
In case of an error like `gpg: key generation failed: Unknown elliptic curve` (a [gnupg bug](https://dev.gnupg.org/T5444)), disable GPG verification before running `make start-local`:
diff --git a/docs/developer-guide/static-code-analysis.md b/docs/developer-guide/static-code-analysis.md
index bdc331c02e..90798a70f5 100644
--- a/docs/developer-guide/static-code-analysis.md
+++ b/docs/developer-guide/static-code-analysis.md
@@ -2,9 +2,9 @@
We use the following static code analysis tools:
-* `golangci-lint` and `eslint` for compile time linting
+* golangci-lint and eslint for compile time linting
* [codecov.io](https://codecov.io/gh/argoproj/argo-cd) - for code coverage
* [snyk.io](https://app.snyk.io/org/argoproj/projects) - for image scanning
* [sonarcloud.io](https://sonarcloud.io/organizations/argoproj/projects) - for code scans and security alerts
-These are at least run daily or on each pull request.
+These are at least run daily or on each pull request.
\ No newline at end of file
diff --git a/docs/developer-guide/test-e2e.md b/docs/developer-guide/test-e2e.md
index e3c50934e9..a1ddec8058 100644
--- a/docs/developer-guide/test-e2e.md
+++ b/docs/developer-guide/test-e2e.md
@@ -3,26 +3,15 @@
The test [directory](https://github.com/argoproj/argo-cd/tree/master/test) contains E2E tests and test applications. The tests assume that Argo CD services are installed into `argocd-e2e` namespace or cluster in current context. A throw-away
namespace `argocd-e2e***` is created prior to the execution of the tests. The throw-away namespace is used as a target namespace for test applications.
-The [/test/e2e/testdata](https://github.com/argoproj/argo-cd/tree/master/test/e2e/testdata) directory contains various Argo CD applications. Before test execution, the directory is copied into `/tmp/argo-e2e***` temp directory and used in tests as a
-Git repository via file url: `file:///tmp/argo-e2e***`.
-
-!!! note "Rancher Desktop Volume Sharing"
- The e2e git server runs in a container. If you are using Rancher Desktop, you will need to enable volume sharing for
- the e2e container to access the testdata directory. To do this, add the following to
- `~/Library/Application\ Support/rancher-desktop/lima/_config/override.yaml` and restart Rancher Desktop:
-
- ```yaml
- mounts:
- - location: /private/tmp
- writable: true
- ```
+The [/test/e2e/testdata](https://github.com/argoproj/argo-cd/tree/master/test/e2e/testdata) directory contains various Argo CD applications. Before test execution directory is copies into `/tmp/argocd-e2e***` temp directory and used in tests as a
+Git repository via file url: `file:///tmp/argocd-e2e***`.
## Running Tests Locally
1. Start the e2e version `make start-e2e`
2. Run the tests: `make test-e2e`
-You can observe the tests by using the UI [http://localhost:4000/applications](http://localhost:4000/applications) with username `"admin"` and password `"password"`.
+You can observe the tests by using the UI [http://localhost:8080/applications](http://localhost:8080/applications) with username `"admin"` and password `"password"`.
## Configuration of E2E Tests execution
@@ -42,7 +31,7 @@ If you have changed the port for `argocd-server`, be sure to also set `ARGOCD_SE
Some effort has been made to balance test isolation with speed. Tests are isolated as follows as each test gets:
* A random 5 character ID.
-* A unique Git repository containing the `testdata` in `/tmp/argo-e2e/${id}`.
+* A unique Git repository containing the `testdata` in `/tmp/argocd-e2e/${id}`.
* A namespace `argocd-e2e-ns-${id}`.
* A primary name for the app `argocd-e2e-${id}`.
diff --git a/docs/developer-guide/toolchain-guide.md b/docs/developer-guide/toolchain-guide.md
index c2e1c3f960..9bba72b456 100644
--- a/docs/developer-guide/toolchain-guide.md
+++ b/docs/developer-guide/toolchain-guide.md
@@ -16,7 +16,7 @@ If you want to submit a PR, please read this document carefully, as it contains
As is the case with the development process, this document is under constant change. If you notice any error, or if you think this document is out-of-date, or if you think it is missing something: Feel free to submit a PR or submit a bug to our GitHub issue tracker.
-If you need guidance with submitting a PR, or have any other questions regarding development of Argo CD, do not hesitate to [join our Slack](https://argoproj.github.io/community/join-slack) and get in touch with us in the `#argo-cd-contributors` channel!
+If you need guidance with submitting a PR, or have any other questions regarding development of Argo CD, do not hesitate to [join our Slack](https://argoproj.github.io/community/join-slack) and get in touch with us in the `#argo-contributors` channel!
## Before you start
@@ -42,6 +42,7 @@ You will need at least the following things in your toolchain in order to develo
When you submit a PR against Argo CD's GitHub repository, a couple of CI checks will be run automatically to ensure your changes will build fine and meet certain quality standards. Your contribution needs to pass those checks in order to be merged into the repository.
!!!note
+
Please make sure that you always create PRs from a branch that is up-to-date with the latest changes from Argo CD's master branch. Depending on how long it takes for the maintainers to review and merge your PR, it might be necessary to pull in latest changes into your branch again.
Please understand that we, as an Open Source project, have limited capacities for reviewing and merging PRs to Argo CD. We will do our best to review your PR and give you feedback as soon as possible, but please bear with us if it takes a little longer as expected.
@@ -94,7 +95,7 @@ ok github.com/argoproj/argo-cd/server/cache 0.029s coverage: 89.3%
## Local vs Virtualized toolchain
-Argo CD provides a fully virtualized development and testing toolchain using Docker images. It is recommended to use those images, as they provide the same runtime environment as the final product, and it is much easier to keep up-to-date with changes to the toolchain and dependencies. But as using Docker comes with a slight performance penalty, you might want to set up a local toolchain.
+Argo CD provides a fully virtualized development and testing toolchain using Docker images. It is recommended to use those images, as they provide the same runtime environment as the final product and it is much easier to keep up-to-date with changes to the toolchain and dependencies. But as using Docker comes with a slight performance penalty, you might want to setup a local toolchain.
Most relevant targets for the build & test cycles in the `Makefile` provide two variants, one of them suffixed with `-local`. For example, `make test` will run unit tests in the Docker container, `make test-local` will run it natively on your local system.
@@ -103,7 +104,7 @@ If you are going to use the virtualized toolchain, please bear in mind the follo
* Your Kubernetes API server must listen on the interface of your local machine or VM, and not on `127.0.0.1` only.
* Your Kubernetes client configuration (`~/.kube/config`) must not use an API URL that points to `localhost` or `127.0.0.1`.
-You can test whether the virtualized toolchain has access to your Kubernetes cluster by running `make verify-kube-connect` (*after* you have set up your development environment, as described below), which will run `kubectl version` inside the Docker container used for running all tests.
+You can test whether the virtualized toolchain has access to your Kubernetes cluster by running `make verify-kube-connect` (*after* you have setup your development environment, as described below), which will run `kubectl version` inside the Docker container used for running all tests.
The Docker container for the virtualized toolchain will use the following local mounts from your workstation, and possibly modify its contents:
@@ -147,10 +148,12 @@ The following steps are required no matter whether you chose to use a virtualize
### Clone the Argo CD repository from your personal fork on GitHub
-* `git clone https://github.com/YOUR-USERNAME/argo-cd`
+* `mkdir -p ~/go/src/github.com/argoproj`
+* `cd ~/go/src/github.com/argoproj`
+* `git clone https://github.com/yourghuser/argo-cd`
* `cd argo-cd`
-### Optional: Set up an additional Git remote
+### Optional: Setup an additional Git remote
While everyone has their own Git workflow, the author of this document recommends to create a remote called `upstream` in your local copy pointing to the original Argo CD repository. This way, you can easily keep your local branches up-to-date by merging in latest changes from the Argo CD repository, i.e. by doing a `git pull upstream master` in your locally checked out branch. To create the remote, run `git remote add upstream https://github.com/argoproj/argo-cd`
@@ -214,7 +217,7 @@ k3d cluster create my-cluster --wait --k3s-arg '--disable=traefik@server:*' --ap
```
!!!note
- For k3d versions less than v5.0.0, the example command flags `--k3s-arg` and `'--disable=traefik@server:*'` should change to `--k3s-server-arg` and `'--disable=traefik'`, respectively.
+For k3d versions less than v5.0.0, the example command flags `--k3s-arg` and `'--disable=traefik@server:*'` should change to `--k3s-server-arg` and `'--disable=traefik'`, respectively.
## The development cycle
@@ -249,7 +252,7 @@ After the code glue has been generated, your code should build and the unit test
* `make build`
* `make test`
-These steps are non-modifying, so there's no need to check for changes afterward.
+These steps are non-modifying, so there's no need to check for changes afterwards.
### Lint your code base
@@ -326,7 +329,7 @@ You need to pull in all required Go dependencies. To do so, run
### Test your build toolchain
-The first thing you can do to test whether your build toolchain is set up correctly is by generating the glue code for the API and after that, run a normal build:
+The first thing you can do to test whether your build toolchain is setup correctly is by generating the glue code for the API and after that, run a normal build:
* `make codegen-local`
* `make build-local`
@@ -335,7 +338,7 @@ This should return without any error.
### Run unit-tests
-The next thing is to make sure that unit tests are running correctly on your system. These will require that all dependencies, such as Helm, Kustomize, Git, GnuPG, etc. are correctly installed and fully functioning:
+The next thing is to make sure that unit tests are running correctly on your system. These will require that all dependencies, such as Helm, Kustomize, Git, GnuPG, etc are correctly installed and fully functioning:
* `make test-local`
@@ -346,6 +349,4 @@ The final step is running the End-to-End testsuite, which makes sure that your K
* First, start the End-to-End server: `make start-e2e-local`. This will spawn a number of processes and services on your system.
* When all components have started, run `make test-e2e-local` to run the end-to-end tests against your local services.
-To run a single test, you can use `TEST_FLAGS="-run TestName" make test-e2e-local`.
-
For more information about End-to-End tests, refer to the [End-to-End test documentation](test-e2e.md).
diff --git a/docs/developer-guide/use-gitpod.md b/docs/developer-guide/use-gitpod.md
index 5c9d0f2146..36f783bdc9 100644
--- a/docs/developer-guide/use-gitpod.md
+++ b/docs/developer-guide/use-gitpod.md
@@ -29,7 +29,7 @@ access Argo CD API/UI from your laptop.
Gitpod is a perfect tool in following cases:
* you are a first-time contributor and eager to start coding;
-* you are traveling and don't want to set up development tools on your laptop;
+* you are traveling and don't want to setup development tools on your laptop;
* you want to review pull request and need to quickly run code from the PR without changing your local setup;
## Limitations
diff --git a/docs/faq.md b/docs/faq.md
index f5f4374433..44c3e25902 100644
--- a/docs/faq.md
+++ b/docs/faq.md
@@ -147,7 +147,7 @@ See [#1482](https://github.com/argoproj/argo-cd/issues/1482).
## How often does Argo CD check for changes to my Git or Helm repository ?
-The default maximum polling interval is 3 minutes (120 seconds + 60 seconds jitter).
+The default polling interval is 3 minutes (180 seconds) with a configurable jitter.
You can change the setting by updating the `timeout.reconciliation` value and the `timeout.reconciliation.jitter` in the [argocd-cm](https://github.com/argoproj/argo-cd/blob/2d6ce088acd4fb29271ffb6f6023dbb27594d59b/docs/operator-manual/argocd-cm.yaml#L279-L282) config map. If there are any Git changes, Argo CD will only update applications with the [auto-sync setting](user-guide/auto_sync.md) enabled. If you set it to `0` then Argo CD will stop polling Git repositories automatically and you can only use alternative methods such as [webhooks](operator-manual/webhook.md) and/or manual syncs for deploying applications.
diff --git a/docs/getting_started.md b/docs/getting_started.md
index 5d3667fd1c..596251b3c2 100644
--- a/docs/getting_started.md
+++ b/docs/getting_started.md
@@ -64,11 +64,6 @@ Change the argocd-server service type to `LoadBalancer`:
```bash
kubectl patch svc argocd-server -n argocd -p '{"spec": {"type": "LoadBalancer"}}'
```
-After a short wait, your cloud provider will assign an external IP address to the service. You can retrieve this IP with:
-
-```bash
-kubectl get svc argocd-server -n argocd -o=jsonpath='{.status.loadBalancer.ingress[0].ip}'
-```
### Ingress
Follow the [ingress documentation](operator-manual/ingress.md) on how to configure Argo CD with ingress.
diff --git a/docs/operator-manual/application.yaml b/docs/operator-manual/application.yaml
index adfb29d076..b38d7fddd5 100644
--- a/docs/operator-manual/application.yaml
+++ b/docs/operator-manual/application.yaml
@@ -119,15 +119,10 @@ spec:
beep: boop-${ARGOCD_APP_REVISION}
# Toggle which enables/disables env variables substitution in commonAnnotations
commonAnnotationsEnvsubst: true
- # Defines if the common label(s) should be applied to resource selectors. It also excludes common labels from
- # templates unless `labelIncludeTemplates` is set to true.
- labelWithoutSelector: false
- # Defines if the common label(s) should be applied to resource templates.
- labelIncludeTemplates: false
forceCommonLabels: false
forceCommonAnnotations: false
images:
- - quay.io/argoprojlabs/argocd-e2e-container:0.2
+ - gcr.io/heptio-images/ks-guestbook-demo:0.2
- my-app=gcr.io/my-repo/my-app:0.1
namespace: custom-namespace
replicas:
@@ -135,8 +130,6 @@ spec:
count: 4
components:
- ../component # relative to the kustomization.yaml (`source.path`).
- # Ignore locally missing component directories when using Kustomize Components. Defaults to false
- ignoreMissingComponents: true
patches:
- target:
kind: Deployment
@@ -236,7 +229,6 @@ spec:
- PruneLast=true # Allow the ability for resource pruning to happen as a final, implicit wave of a sync operation
- RespectIgnoreDifferences=true # When syncing changes, respect fields ignored by the ignoreDifferences configuration
- ApplyOutOfSyncOnly=true # Only sync out-of-sync resources, rather than applying every object in the application
- - SkipDryRunOnMissingResource=true # Allow skip dry run on missing resource
managedNamespaceMetadata: # Sets the metadata for the application namespace. Only valid if CreateNamespace=true (see above), otherwise it's a no-op.
labels: # The labels to set on the application namespace
any: label
diff --git a/docs/operator-manual/applicationset/Appset-Any-Namespace.md b/docs/operator-manual/applicationset/Appset-Any-Namespace.md
index 9bc0eaf360..01efe576d0 100644
--- a/docs/operator-manual/applicationset/Appset-Any-Namespace.md
+++ b/docs/operator-manual/applicationset/Appset-Any-Namespace.md
@@ -117,7 +117,7 @@ It can be achieved by setting the environment variable `ARGOCD_APPLICATIONSET_CO
#### Change workload startup parameters
-In order to enable this feature, the Argo CD administrator must reconfigure the `argocd-applicationset-controller` workloads to add the `--applicationset-namespaces` parameter to the container's startup command.
+In order to enable this feature, the Argo CD administrator must reconfigure the and `argocd-applicationset-controller` workloads to add the `--applicationset-namespaces` parameter to the container's startup command.
### Safely template project
@@ -256,4 +256,4 @@ spec:
- clusters: {} # Automatically use all clusters defined within Argo CD
```
-If you don't want to allow users to discover all clusters with ApplicationSets from other namespaces you may consider deploying ArgoCD in namespace scope or use OPA rules.
+If you don't want to allow users to discover all clusters with ApplicationSets from other namespaces you may consider deploying ArgoCD in namespace scope or use OPA rules.
\ No newline at end of file
diff --git a/docs/operator-manual/applicationset/Controlling-Resource-Modification.md b/docs/operator-manual/applicationset/Controlling-Resource-Modification.md
index c42a6e3265..1636d348cb 100644
--- a/docs/operator-manual/applicationset/Controlling-Resource-Modification.md
+++ b/docs/operator-manual/applicationset/Controlling-Resource-Modification.md
@@ -35,7 +35,7 @@ spec:
- Policy `create-only`: Prevents ApplicationSet controller from modifying or deleting Applications. **WARNING**: It doesn't prevent Application controller from deleting Applications according to [ownerReferences](https://kubernetes.io/docs/concepts/overview/working-with-objects/owners-dependents/) when deleting ApplicationSet.
- Policy `create-update`: Prevents ApplicationSet controller from deleting Applications. Update is allowed. **WARNING**: It doesn't prevent Application controller from deleting Applications according to [ownerReferences](https://kubernetes.io/docs/concepts/overview/working-with-objects/owners-dependents/) when deleting ApplicationSet.
- Policy `create-delete`: Prevents ApplicationSet controller from modifying Applications. Delete is allowed.
-- Policy `sync`: Create, Update and Delete are allowed.
+- Policy `sync`: Update and Delete are allowed.
If the controller parameter `--policy` is set, it takes precedence on the field `applicationsSync`. It is possible to allow per ApplicationSet sync policy by setting variable `ARGOCD_APPLICATIONSET_CONTROLLER_ENABLE_POLICY_OVERRIDE` to argocd-cmd-params-cm `applicationsetcontroller.enable.policy.override` or directly with controller parameter `--enable-policy-override` (default to `false`).
diff --git a/docs/operator-manual/applicationset/Generators-Git.md b/docs/operator-manual/applicationset/Generators-Git.md
index a03d10e7eb..569eb60034 100644
--- a/docs/operator-manual/applicationset/Generators-Git.md
+++ b/docs/operator-manual/applicationset/Generators-Git.md
@@ -8,7 +8,6 @@ The Git generator contains two subtypes: the Git directory generator, and Git fi
For ApplicationSets with a templated `project` field, [the source of truth _must_ be controlled by admins](./Security.md#templated-project-field)
- in the case of git generators, PRs must require admin approval.
- Git generator does not support Signature Verification For ApplicationSets with a templated `project` field.
- - You must only use "non-scoped" repositories for ApplicationSets with a templated `project` field (see ["Repository Credentials for Applicationsets" below](#repository-credentials-for-applicationsets)).
## Git Generator: Directories
@@ -205,7 +204,7 @@ spec:
You may pass additional, arbitrary string key-value pairs via the `values` field of the git directory generator. Values added via the `values` field are added as `values.(field)`.
-In this example, a `cluster` parameter value is passed. It is interpolated from the `path` variable, to then be used to determine the destination namespace.
+In this example, a `cluster` parameter value is passed. It is interpolated from the `branch` and `path` variable, to then be used to determine the destination namespace.
```yaml
apiVersion: argoproj.io/v1alpha1
kind: ApplicationSet
@@ -222,7 +221,7 @@ spec:
directories:
- path: '*'
values:
- cluster: '{{.path.basename}}'
+ cluster: '{{.branch}}-{{.path.basename}}'
template:
metadata:
name: '{{.path.basename}}'
@@ -342,45 +341,6 @@ The filename can always be accessed using `{{.path.filename}}`.
**Note**: The default behavior of the Git file generator is very greedy. Please see [Git File Generator Globbing](./Generators-Git-File-Globbing.md) for more information.
-### Exclude files
-
-The Git file generator also supports an `exclude` option in order to exclude files in the repository from being scanned by the ApplicationSet controller:
-
-```yaml
-apiVersion: argoproj.io/v1alpha1
-kind: ApplicationSet
-metadata:
- name: guestbook
-spec:
- goTemplate: true
- goTemplateOptions: ["missingkey=error"]
- generators:
- - git:
- repoURL: https://github.com/argoproj/argo-cd.git
- revision: HEAD
- files:
- - path: "applicationset/examples/git-generator-files-discovery/cluster-config/**/config.json"
- - path: "applicationset/examples/git-generator-files-discovery/cluster-config/*/dev/config.json"
- exclude: true
- template:
- metadata:
- name: '{{.cluster.name}}-guestbook'
- spec:
- project: default
- source:
- repoURL: https://github.com/argoproj/argo-cd.git
- targetRevision: HEAD
- path: "applicationset/examples/git-generator-files-discovery/apps/guestbook"
- destination:
- server: https://kubernetes.default.svc
- #server: '{{.cluster.address}}'
- namespace: guestbook
-```
-
-This example excludes the `config.json` file in the `dev` directory from the list of files scanned for this `ApplicationSet` resource.
-
-(*The full example can be found [here](https://github.com/argoproj/argo-cd/tree/master/applicationset/examples/git-generator-files-discovery/excludes).*)
-
### Pass additional key-value pairs via `values` field
You may pass additional, arbitrary string key-value pairs via the `values` field of the git files generator. Values added via the `values` field are added as `values.(field)`.
@@ -424,28 +384,10 @@ In `values` we can also interpolate all fields set by the git files generator as
## Webhook Configuration
-When using a Git generator, the ApplicationSet controller polls Git repositories every 3 minutes (this can be customized per ApplicationSet with `requeueAfterSeconds`) to detect changes. To eliminate
+When using a Git generator, ApplicationSet polls Git repositories every three minutes to detect changes. To eliminate
this delay from polling, the ApplicationSet webhook server can be configured to receive webhook events. ApplicationSet supports
Git webhook notifications from GitHub and GitLab. The following explains how to configure a Git webhook for GitHub, but the same process should be applicable to other providers.
-```yaml
-apiVersion: argoproj.io/v1alpha1
-kind: ApplicationSet
-metadata:
- name: guestbook
- namespace: argocd
-spec:
- goTemplate: true
- goTemplateOptions: ["missingkey=error"]
- generators:
- - git:
- # When using a Git generator, the ApplicationSet controller polls every `requeueAfterSeconds` interval (defaulting to every 3 minutes) to detect changes.
- requeueAfterSeconds: 180
- repoURL: https://github.com/argoproj/argo-cd.git
- revision: HEAD
- # ...
-```
-
!!! note
The ApplicationSet controller webhook does not use the same webhook as the API server as defined [here](../webhook.md). ApplicationSet exposes a webhook server as a service of type ClusterIP. An ApplicationSet specific Ingress resource needs to be created to expose this service to the webhook source.
@@ -503,8 +445,7 @@ stringData:
After saving, please restart the ApplicationSet pod for the changes to take effect.
## Repository credentials for ApplicationSets
-If your [ApplicationSets](index.md) uses a repository where you need credentials to be able to access it _and_ if the
-ApplicationSet project field is templated (i.e. the `project` field of the ApplicationSet contains `{{ ... }}`), you need to add the repository as a "non project scoped" repository.
+If your [ApplicationSets](index.md) uses a repository where you need credentials to be able to access it, you need to add the repository as a "non project scoped" repository.
- When doing that through the UI, set this to a **blank** value in the dropdown menu.
- When doing that through the CLI, make sure you **DO NOT** supply the parameter `--project` ([argocd repo add docs](../../user-guide/commands/argocd_repo_add.md))
- When doing that declaratively, make sure you **DO NOT** have `project:` defined under `stringData:` ([complete yaml example](../argocd-repositories-yaml.md))
diff --git a/docs/operator-manual/applicationset/Generators-Matrix.md b/docs/operator-manual/applicationset/Generators-Matrix.md
index ca6afdfd66..91b1bb3abb 100644
--- a/docs/operator-manual/applicationset/Generators-Matrix.md
+++ b/docs/operator-manual/applicationset/Generators-Matrix.md
@@ -420,3 +420,14 @@ For example, the below example would be invalid (cluster-generator must come aft
revision: HEAD
files:
- path: "examples/git-generator-files-discovery/cluster-config/engineering/{{.name}}**/config.json" # {{.name}} is produced by cluster generator
+
+1. When using a Matrix generator nested inside another Matrix or Merge generator, [Post Selectors](Generators-Post-Selector.md) for this nested generator's generators will only be applied when enabled via `spec.applyNestedSelectors`. You may also need to enable this even if your Post Selectors are not within the nested matrix or Merge generator, but are instead a sibling of a nested Matrix or Merge generator.
+
+ - matrix:
+ generators:
+ - matrix:
+ generators:
+ - list
+ elements:
+ - # (...)
+ selector: { } # Only applied when applyNestedSelectors is true
diff --git a/docs/operator-manual/applicationset/Generators-Merge.md b/docs/operator-manual/applicationset/Generators-Merge.md
index 8b15302d0d..b2ccfe86fb 100644
--- a/docs/operator-manual/applicationset/Generators-Merge.md
+++ b/docs/operator-manual/applicationset/Generators-Merge.md
@@ -219,3 +219,14 @@ Assuming a cluster named `germany01` with the label `metadata.labels.location=Ge
- merge:
mergeKeys:
- values.merge
+
+1. When using a Merge generator nested inside another Matrix or Merge generator, [Post Selectors](Generators-Post-Selector.md) for this nested generator's generators will only be applied when enabled via `spec.applyNestedSelectors`.
+
+ - merge:
+ generators:
+ - merge:
+ generators:
+ - list
+ elements:
+ - # (...)
+ selector: { } # Only applied when applyNestedSelectors is true
diff --git a/docs/operator-manual/applicationset/Generators-Pull-Request.md b/docs/operator-manual/applicationset/Generators-Pull-Request.md
index 054d72cb33..2e6dffaaf5 100644
--- a/docs/operator-manual/applicationset/Generators-Pull-Request.md
+++ b/docs/operator-manual/applicationset/Generators-Pull-Request.md
@@ -112,7 +112,7 @@ spec:
* `api`: If using self-hosted GitLab, the URL to access it. (Optional)
* `tokenRef`: A `Secret` name and key containing the GitLab access token to use for requests. If not specified, will make anonymous requests which have a lower rate limit and can only see public repositories. (Optional)
* `labels`: Labels is used to filter the MRs that you want to target. (Optional)
-* `pullRequestState`: PullRequestState is an additional MRs filter to get only those with a certain state. By default all states. Default: "" (all states). Valid values: `""`, `opened`, `closed`, `merged` or `locked`. (Optional)
+* `pullRequestState`: PullRequestState is an additional MRs filter to get only those with a certain state. Default: "" (all states)
* `insecure`: By default (false) - Skip checking the validity of the SCM's certificate - useful for self-signed TLS certificates.
* `caRef`: Optional `ConfigMap` name and key containing the GitLab certificates to trust - useful for self-signed TLS certificates. Possibly reference the ArgoCD CM holding the trusted certs.
@@ -262,14 +262,6 @@ spec:
# Filter PRs using the source branch name. (optional)
filters:
- branchMatch: ".*-argocd"
-
- # If you need to filter destination branch too, you can use this
- - targetBranchMatch: "master"
-
- # Also you can combine source and target branch filters like
- # This case will match any pull-request where source branch ends with "-argocd" and destination branch is master
- - branchMatch: ".*-argocd"
- targetBranchMatch: "master"
template:
# ...
```
@@ -277,12 +269,7 @@ spec:
- `owner`: Required name of the Bitbucket workspace
- `repo`: Required name of the Bitbucket repository.
- `api`: Optional URL to access the Bitbucket REST API. For the example above, an API request would be made to `https://api.bitbucket.org/2.0/repositories/{workspace}/{repo_slug}/pullrequests`. If not set, defaults to `https://api.bitbucket.org/2.0`
-
-You can use branch `filters` like
-- `branchMatch`: Optional regexp filter which should match the source branch name.
-- `targetBranchMatch`: Optional regexp filter which should match destination branch name.
-
-> Note: Labels are not supported by Bitbucket.
+- `branchMatch`: Optional regexp filter which should match the source branch name. This is an alternative to labels which are not supported by Bitbucket server.
If you want to access a private repository, Argo CD will need credentials to access repository in Bitbucket Cloud. You can use Bitbucket App Password (generated per user, with access to whole workspace), or Bitbucket App Token (generated per repository, with access limited to repository scope only). If both App Password and App Token are defined, App Token will be used.
@@ -493,39 +480,3 @@ For more information about each event, please refer to the [official documentati
## Lifecycle
An Application will be generated when a Pull Request is discovered when the configured criteria is met - i.e. for GitHub when a Pull Request matches the specified `labels` and/or `pullRequestState`. Application will be removed when a Pull Request no longer meets the specified criteria.
-
-## Pass additional key-value pairs via `values` field
-
-You may pass additional, arbitrary string key-value pairs via the `values` field of any Pull Request generator. Values added via the `values` field are added as `values.(field)`.
-
-```yaml
-apiVersion: argoproj.io/v1alpha1
-kind: ApplicationSet
-metadata:
- name: myapps
-spec:
- goTemplate: true
- goTemplateOptions: ["missingkey=error"]
- generators:
- - pullRequest:
- # ...
- values:
- pr_branch: '{{ .branch }}'
- template:
- metadata:
- name: '{{ .values.name }}'
- spec:
- source:
- repoURL: '{{ .url }}'
- targetRevision: '{{ .branch }}'
- path: kubernetes/
- project: default
- destination:
- server: https://kubernetes.default.svc
- namespace: default
-```
-
-!!! note
- The `values.` prefix is always prepended to values provided via `generators.pullRequest.values` field. Ensure you include this prefix in the parameter name within the `template` when using it.
-
-In `values` we can also interpolate all fields set by the Pull Request generator as mentioned above.
diff --git a/docs/operator-manual/applicationset/Generators-SCM-Provider.md b/docs/operator-manual/applicationset/Generators-SCM-Provider.md
index a816618780..d48c074035 100644
--- a/docs/operator-manual/applicationset/Generators-SCM-Provider.md
+++ b/docs/operator-manual/applicationset/Generators-SCM-Provider.md
@@ -442,7 +442,6 @@ spec:
* `organization`: The name of the organization the repository is in.
* `repository`: The name of the repository.
-* `repository_id`: The id of the repository.
* `url`: The clone URL for the repository.
* `branch`: The default branch of the repository.
* `sha`: The Git commit SHA for the branch.
diff --git a/docs/operator-manual/applicationset/Template.md b/docs/operator-manual/applicationset/Template.md
index ba15753f6b..6bc6f24dc0 100644
--- a/docs/operator-manual/applicationset/Template.md
+++ b/docs/operator-manual/applicationset/Template.md
@@ -169,10 +169,6 @@ spec:
{{- end }}
```
-!!! important
- `templatePatch` only works when [go templating](../applicationset/GoTemplate.md) is enabled.
- This means that the `goTemplate` field under `spec` needs to be set to `true` for template patching to work.
-
!!! important
The `templatePatch` can apply arbitrary changes to the template. If parameters include untrustworthy user input, it
may be possible to inject malicious changes into the template. It is recommended to use `templatePatch` only with
diff --git a/docs/operator-manual/argocd-cm.yaml b/docs/operator-manual/argocd-cm.yaml
index e2fb98cd93..68b4c0c730 100644
--- a/docs/operator-manual/argocd-cm.yaml
+++ b/docs/operator-manual/argocd-cm.yaml
@@ -88,8 +88,8 @@ data:
# Configuration to customize resource behavior (optional) can be configured via splitted sub keys.
# Keys are in the form: resource.customizations.ignoreDifferences., resource.customizations.health.
- # resource.customizations.actions., resource.customizations.knownTypeFields.
- # resource.customizations.ignoreResourceUpdates.
+ # resource.customizations.actions., resource.customizations.knownTypeFields.
+ # resource.customizations.ignoreResourceUpdates.
resource.customizations.ignoreDifferences.admissionregistration.k8s.io_MutatingWebhookConfiguration: |
jsonPointers:
- /webhooks/0/clientConfig/caBundle
@@ -133,7 +133,7 @@ data:
- /metadata/annotations/autoscaling.alpha.kubernetes.io~1metrics
- /metadata/annotations/autoscaling.alpha.kubernetes.io~1current-metrics
- resource.customizations.health.certmanager.k8s.io_Certificate: |
+ resource.customizations.health.certmanager.k8s.io-Certificate: |
hs = {}
if obj.status ~= nil then
if obj.status.conditions ~= nil then
@@ -237,15 +237,16 @@ data:
# An optional comma-separated list of metadata.labels keys to exclude from Kubernetes events generated for Applications. Supports wildcards.
resource.excludeEventLabelKeys: environment,bu
+
resource.compareoptions: |
# if ignoreAggregatedRoles set to true then differences caused by aggregated roles in RBAC resources are ignored.
ignoreAggregatedRoles: true
# disables status field diffing in specified resource types
- # 'crd' - CustomResourceDefinitions
- # 'all' - all resources (default)
+ # 'crd' - CustomResourceDefinitions (default)
+ # 'all' - all resources
# 'none' - disabled
- ignoreResourceStatusField: all
+ ignoreResourceStatusField: crd
# configuration to instruct controller to only watch for resources that it has permissions to list
# can be either empty, "normal" or "strict". By default, it is empty i.e. disabled.
@@ -280,9 +281,9 @@ data:
# You can change the resource tracking method Argo CD uses by changing the
# setting application.resourceTrackingMethod to the desired method.
# The following methods are available:
+ # - label : Uses the application.instanceLabelKey label for tracking
# - annotation : Uses an annotation with additional metadata for tracking instead of the label
# - annotation+label : Also uses an annotation for tracking, but additionally labels the resource with the application name
- # - label : Uses the application.instanceLabelKey label for tracking
application.resourceTrackingMethod: annotation
# Optional installation id. Allows to have multiple installations of Argo CD in the same cluster.
@@ -325,18 +326,17 @@ data:
# at the bottom of the page. Change the value as needed.
# ui.bannerposition: "bottom"
- # Application reconciliation timeout is the amount of time spent before Argo tries to discover if a new manifests version got
- # published to the repository. Reconciliation by timeout is disabled if timeout is set to 0. Two minutes by default with additional jitter.
+ # Application reconciliation timeout is the max amount of time required to discover if a new manifests version got
+ # published to the repository. Reconciliation by timeout is disabled if timeout is set to 0. Three minutes by default.
# > Note: The argocd-repo-server deployment and the argocd-application-controller statefulset (or deployment, if
# configured) must be manually restarted after changing the setting.
- timeout.reconciliation: 120s
-
+ timeout.reconciliation: 180s
# With a large number of applications, the periodic refresh for each application can cause a spike in the refresh queue
# and can cause a spike in the repo-server component. To avoid this, you can set a jitter to the sync timeout, which will
# spread out the refreshes and give time to the repo-server to catch up. The jitter is the maximum duration that can be
# added to the sync timeout. So, if the sync timeout is 3 minutes and the jitter is 1 minute, then the actual timeout will
- # be between 3 and 4 minutes. Disabled when the value is 0, defaults to 1 minute.
- timeout.reconciliation.jitter: 60s
+ # be between 3 and 4 minutes. Disabled when the value is 0, defaults to 0.
+ timeout.reconciliation.jitter: "0"
# cluster.inClusterEnabled indicates whether to allow in-cluster server address. This is enabled by default.
cluster.inClusterEnabled: "true"
@@ -345,6 +345,12 @@ data:
# This is to prevent the UI from becoming unresponsive when rendering a large number of logs. Default is 10.
server.maxPodLogsToRender: "10"
+ # Application pod logs RBAC enforcement enables control over who can and who can't view application pod logs.
+ # When you enable the switch, pod logs will be visible only to admin role by default. Other roles/users will not be able to view them via cli and UI.
+ # When you enable the switch, viewing pod logs for other roles/users will require explicit RBAC allow policies (allow get on logs subresource).
+ # When you disable the switch (either add it to the configmap with a "false" value or do not add it to the configmap), no actual RBAC enforcement will take place.
+ server.rbac.log.enforce.enable: "false"
+
# exec.enabled indicates whether the UI exec feature is enabled. It is disabled by default.
exec.enabled: "false"
@@ -429,4 +435,4 @@ data:
webhook.maxPayloadSizeMB: "50"
# application.sync.impersonation.enabled enables application sync to use a custom service account, via impersonation. This allows decoupling sync from control-plane service account.
- application.sync.impersonation.enabled: "false"
\ No newline at end of file
+ application.sync.impersonation.enabled: "false"
diff --git a/docs/operator-manual/argocd-cmd-params-cm.yaml b/docs/operator-manual/argocd-cmd-params-cm.yaml
index 33e0e7c4b3..59382a30e9 100644
--- a/docs/operator-manual/argocd-cmd-params-cm.yaml
+++ b/docs/operator-manual/argocd-cmd-params-cm.yaml
@@ -28,8 +28,6 @@ data:
otlp.insecure: "true"
# Open-Telemetry collector headers: (e.g. "key1=value1,key2=value2")
otlp.headers: ""
- # Open-Telemetry collector attrs: (e.g. "key1:value1,key2:value2")
- otlp.attrs: ""
# List of additional namespaces where applications may be created in and
# reconciled from. The namespace where Argo CD is installed to will always
@@ -38,11 +36,6 @@ data:
# Feature state: Beta
application.namespaces: ns1, ns2, ns3
- # Set the logging timestamp format. The default is "" which means "2006-01-02T15:04:05Z07:00" (RFC3339).
- # See https://pkg.go.dev/time#pkg-constants for more options.
- # This option is used for all components.
- log.format.timestamp: ""
-
## Controller Properties
# Repo server RPC call timeout seconds.
controller.repo.server.timeout.seconds: "60"
@@ -54,8 +47,8 @@ data:
controller.status.processors: "20"
# Number of application operation processors (default 10)
controller.operation.processors: "10"
- # Set the logging format. One of: json|text (default "json")
- controller.log.format: "json"
+ # Set the logging format. One of: text|json (default "text")
+ controller.log.format: "text"
# Set the logging level. One of: debug|info|warn|error (default "info")
controller.log.level: "info"
# Prometheus metrics cache expiration (disabled by default. e.g. 24h0m0s)
@@ -69,10 +62,11 @@ data:
# Cache expiration for app state (default 1h0m0s)
controller.app.state.cache.expiration: "1h0m0s"
- # Specifies if resource health should be persisted in the application CR (default false).
- # Setting this to true will store the health status of each resource in the application CR,
- # increasing the number of updates to the CR and putting more load on the application controller
- controller.resource.health.persist: "false"
+ # Specifies if resource health should be persisted in app CRD (default true)
+ # Changing this to `false` significantly reduce number of Application CRD updates and improves controller performance.
+ # However, disabling resource health by default might affect applications that communicate with Applications CRD directly
+ # so we have to defer switching this to `false` by default till v3.0 release.
+ controller.resource.health.persist: "true"
# Cache expiration default (default 24h0m0s)
controller.default.cache.expiration: "24h0m0s"
# Sharding algorithm used to balance clusters across application controller shards (default "legacy")
@@ -93,7 +87,7 @@ data:
controller.profile.enabled: "false"
# Enables batch-processing mode in the controller's cluster cache. This can help improve performance for clusters that
# have high "churn," i.e. lots of resource modifications.
- controller.cluster.cache.batch.events.processing: "true"
+ controller.cluster.cache.batch.events.processing: "false"
# This sets the interval at which the controller's cluster cache processes a batch of cluster events. A lower value
# will increase the speed at which Argo CD becomes aware of external cluster state. A higher value will reduce cluster
# cache lock contention and better handle high-churn clusters.
@@ -121,11 +115,9 @@ data:
server.api.content.types: "application/json"
# Number of webhook requests processed concurrently (default 50)
server.webhook.parallelism.limit: "50"
- # Whether to allow sync with replace checked to go through. Resource-level annotation to replace override this setting, i.e. it's only enforced on the API server level.
- server.sync.replace.allowed: "true"
- # Set the logging format. One of: json|text (default "json")
- server.log.format: "json"
+ # Set the logging format. One of: text|json (default "text")
+ server.log.format: "text"
# Set the logging level. One of: debug|info|warn|error (default "info")
server.log.level: "info"
# Repo server RPC call timeout seconds. (default 60)
@@ -172,8 +164,8 @@ data:
reposerver.listen.address: "0.0.0.0"
# Listen on given address for metrics (default "0.0.0.0")
reposerver.metrics.listen.address: "0.0.0.0"
- # Set the logging format. One of: json|text (default "json")
- reposerver.log.format: "json"
+ # Set the logging format. One of: text|json (default "text")
+ reposerver.log.format: "text"
# Set the logging level. One of: debug|info|warn|error (default "info")
reposerver.log.level: "info"
# Limit on number of concurrent manifests generate requests. Any value less the 1 means no limit.
@@ -219,15 +211,15 @@ data:
## Commit-server properties
# Listen on given address for incoming connections (default "0.0.0.0")
commitserver.listen.address: "0.0.0.0"
- # Set the logging format. One of: json|text (default "json")
- commitserver.log.format: "json"
+ # Set the logging format. One of: text|json (default "text")
+ commitserver.log.format: "text"
# Set the logging level. One of: debug|info|warn|error (default "info")
commitserver.log.level: "info"
# Listen on given address for metrics (default "0.0.0.0")
commitserver.metrics.listen.address: "0.0.0.0"
- # Set the logging format. One of: json|text (default "json")
- dexserver.log.format: "json"
+ # Set the logging format. One of: text|json (default "text")
+ dexserver.log.format: "text"
# Set the logging level. One of: debug|info|warn|error (default "info")
dexserver.log.level: "info"
# Disable TLS on the HTTP endpoint
@@ -253,8 +245,8 @@ data:
applicationsetcontroller.enable.new.git.file.globbing: "false"
# Print debug logs. Takes precedence over loglevel
applicationsetcontroller.debug: "false"
- # Set the logging format. One of: json|text (default "json")
- applicationsetcontroller.log.format: "json"
+ # Set the logging format. One of: text|json (default "text")
+ applicationsetcontroller.log.format: "text"
# Set the logging level. One of: debug|info|warn|error (default "info")
applicationsetcontroller.log.level: "info"
# Enable dry run mode
@@ -280,16 +272,12 @@ data:
applicationsetcontroller.requeue.after: "3m"
# Enable strict mode for tokenRef in ApplicationSet resources. When enabled, the referenced secret must have a label `argocd.argoproj.io/secret-type` with value `scm-creds`.
applicationsetcontroller.enable.tokenref.strict.mode: "false"
- # Comma delimited list of annotations to preserve in generated applications
- applicationsetcontroller.global.preserved.annotations: "acme.com/annotation1,acme.com/annotation2"
- # Comma delimited list of labels to preserve in generated applications
- applicationsetcontroller.global.preserved.labels: "acme.com/label1,acme.com/label2"
## Argo CD Notifications Controller Properties
# Set the logging level. One of: debug|info|warn|error (default "info")
notificationscontroller.log.level: "info"
- # Set the logging format. One of: json|text (default "json")
- notificationscontroller.log.format: "json"
+ # Set the logging format. One of: text|json (default "text")
+ notificationscontroller.log.format: "text"
# Enable self-service notifications config. Used in conjunction with apps-in-any-namespace. (default "false")
notificationscontroller.selfservice.enabled: "false"
# Disable TLS on connections to repo server
diff --git a/docs/operator-manual/argocd-rbac-cm-yaml.md b/docs/operator-manual/argocd-rbac-cm-yaml.md
index bafd65bbe3..c0dbcde428 100644
--- a/docs/operator-manual/argocd-rbac-cm-yaml.md
+++ b/docs/operator-manual/argocd-rbac-cm-yaml.md
@@ -1,7 +1,5 @@
# argocd-rbac-cm.yaml example
-**Note**: While policy files are CSV files, ArgoCD ignores lines starting with `#` when parsing the file, allowing for line comments starting with #.
-
An example of an argocd-rbac-cm.yaml file:
```yaml
diff --git a/docs/operator-manual/argocd-repositories.yaml b/docs/operator-manual/argocd-repositories.yaml
index 66f7980fb4..8f48429ebd 100644
--- a/docs/operator-manual/argocd-repositories.yaml
+++ b/docs/operator-manual/argocd-repositories.yaml
@@ -12,7 +12,6 @@ stringData:
url: https://github.com/argoproj/argocd-example-apps
password: my-password
username: my-username
- bearerToken: my-token
project: my-project
insecure: "true" # Ignore validity of server's TLS certificate. Defaults to "false"
forceHttpBasicAuth: "true" # Skip auth method negotiation and force usage of HTTP basic auth. Defaults to "false"
@@ -69,19 +68,4 @@ metadata:
labels:
argocd.argoproj.io/secret-type: repository
stringData:
- url: https://github.com/argoproj/private-repo
----
-apiVersion: v1
-kind: Secret
-metadata:
- name: aci-private-repo
- namespace: argocd
- labels:
- argocd.argoproj.io/secret-type: repository
-stringData:
- type: helm
- url: contoso.azurecr.io/charts
- name: contosocharts
- enableOCI: "true"
- useAzureWorkloadIdentity: "true"
-
\ No newline at end of file
+ url: https://github.com/argoproj/private-repo
\ No newline at end of file
diff --git a/docs/operator-manual/config-management-plugins.md b/docs/operator-manual/config-management-plugins.md
index 9cc14df34f..b38635feb8 100644
--- a/docs/operator-manual/config-management-plugins.md
+++ b/docs/operator-manual/config-management-plugins.md
@@ -519,10 +519,6 @@ call from the config management sidecar container to the reposerver to retrieve
Utilizing `ASKPASS` means that credentials are not proactively shared, but rather only provided when an operation requires
them.
-`ASKPASS` requires a socket to be shared between the config management plugin and the reposerver. To mitigate path traversal
-attacks, it's recommended to use a dedicated volume to share the socket, and mount it in the reposerver and sidecar.
-To change the socket path, you must set the `ARGOCD_ASK_PASS_SOCK` environment variable for both containers.
-
To allow the plugin to access the reposerver git credentials, you can set `provideGitCreds` to `true` in the plugin spec:
!!! warning
diff --git a/docs/operator-manual/core.md b/docs/operator-manual/core.md
index edf6025318..79b2530cfe 100644
--- a/docs/operator-manual/core.md
+++ b/docs/operator-manual/core.md
@@ -78,9 +78,8 @@ the process) invoking the CLI needs to have access to the Argo CD
namespace with the proper permission in the `Application` and
`ApplicationSet` resources for executing a given command.
-To use [Argo CD CLI](https://argo-cd.readthedocs.io/en/stable/cli_installation) in core mode, it is required to pass the `--core`
-flag with the `login` subcommand. The `--core` flag is responsible for spawning a local Argo CD API server
-process that handles CLI and Web UI requests.
+To use Argo CD CLI in core mode, it is required to pass the `--core`
+flag with the `login` subcommand.
Example:
@@ -98,3 +97,4 @@ argocd admin dashboard -n argocd
```
Argo CD Web UI will be available at `http://localhost:8080`
+
diff --git a/docs/operator-manual/custom_tools.md b/docs/operator-manual/custom_tools.md
index d23b0a23fa..e94a1d5ac6 100644
--- a/docs/operator-manual/custom_tools.md
+++ b/docs/operator-manual/custom_tools.md
@@ -30,7 +30,7 @@ the helm binary with a different version than what is bundled in Argo CD:
image: alpine:3.8
command: [sh, -c]
args:
- - wget -qO- https://get.helm.sh/helm-v2.12.3-linux-amd64.tar.gz | tar -xvzf - &&
+ - wget -qO- https://storage.googleapis.com/kubernetes-helm/helm-v2.12.3-linux-amd64.tar.gz | tar -xvzf - &&
mv linux-amd64/helm /custom-tools/
volumeMounts:
- mountPath: /custom-tools
diff --git a/docs/operator-manual/declarative-setup.md b/docs/operator-manual/declarative-setup.md
index aea5e3835a..d3b93d27c1 100644
--- a/docs/operator-manual/declarative-setup.md
+++ b/docs/operator-manual/declarative-setup.md
@@ -71,7 +71,6 @@ See [application.yaml](application.yaml) for additional fields. As long as you h
```yaml
spec:
- project: default
source:
repoURL: https://argoproj.github.io/argo-helm
chart: argo
@@ -288,10 +287,6 @@ stringData:
!!! tip
The Kubernetes documentation has [instructions for creating a secret containing a private key](https://kubernetes.io/docs/concepts/configuration/secret/#use-case-pod-with-ssh-keys).
-Example for Azure Container Registry/ Azure Devops repositories using Azure workload identity:
-
-Refer to [Azure Container Registry/Azure Repos using Azure Workload Identity](../user-guide/private-repositories.md#azure-container-registryazure-repos-using-azure-workload-identity)
-
### Repository Credentials
If you want to use the same credentials for multiple repositories, you can configure credential templates. Credential templates can carry the same credentials information as repositories.
@@ -498,6 +493,43 @@ stringData:
A note on noProxy: Argo CD uses exec to interact with different tools such as helm and kustomize. Not all of these tools support the same noProxy syntax as the [httpproxy go package](https://cs.opensource.google/go/x/net/+/internal-branch.go1.21-vendor:http/httpproxy/proxy.go;l=38-50) does. In case you run in trouble with noProxy not beeing respected you might want to try using the full domain instead of a wildcard pattern or IP range to find a common syntax that all tools support.
+### Legacy behaviour
+
+In Argo CD version 2.0 and earlier, repositories were stored as part of the `argocd-cm` config map. For
+backward-compatibility, Argo CD will still honor repositories in the config map, but this style of repository
+configuration is deprecated and support for it will be removed in a future version.
+
+```yaml
+apiVersion: v1
+kind: ConfigMap
+data:
+ repositories: |
+ - url: https://github.com/argoproj/my-private-repository
+ passwordSecret:
+ name: my-secret
+ key: password
+ usernameSecret:
+ name: my-secret
+ key: username
+ repository.credentials: |
+ - url: https://github.com/argoproj
+ passwordSecret:
+ name: my-secret
+ key: password
+ usernameSecret:
+ name: my-secret
+ key: username
+---
+apiVersion: v1
+kind: Secret
+metadata:
+ name: my-secret
+ namespace: argocd
+stringData:
+ password: my-password
+ username: my-username
+```
+
## Clusters
Cluster credentials are stored in secrets same as repositories or repository credentials. Each secret must have label
@@ -507,10 +539,10 @@ The secret data must include following fields:
* `name` - cluster name
* `server` - cluster api server url
-* `namespaces` - optional comma-separated list of namespaces which are accessible in that cluster. Setting namespace values will cause cluster-level resources to be ignored unless `clusterResources` is set to `true`.
-* `clusterResources` - optional boolean string (`"true"` or `"false"`) determining whether Argo CD can manage cluster-level resources on this cluster. This setting is only used when namespaces are restricted using the `namespaces` list.
+* `namespaces` - optional comma-separated list of namespaces which are accessible in that cluster. Cluster level resources would be ignored if namespace list is not empty.
+* `clusterResources` - optional boolean string (`"true"` or `"false"`) determining whether Argo CD can manage cluster-level resources on this cluster. This setting is used only if the list of managed namespaces is not empty.
* `project` - optional string to designate this as a project-scoped cluster.
-* `config` - JSON representation of the following data structure:
+* `config` - JSON representation of following data structure:
```yaml
# Basic authentication settings
@@ -555,14 +587,7 @@ tlsClientConfig:
disableCompression: boolean
```
-!!! important
- When `namespaces` is set, Argo CD will perform a separate list/watch operation for each namespace. This can cause
- the Application controller to exceed the maximum number of idle connections allowed for the Kubernetes API server.
- To resolve this issue, you can increase the `ARGOCD_K8S_CLIENT_MAX_IDLE_CONNECTIONS` environment variable in the
- Application controller.
-
-!!! important
- Note that if you specify a command to run under `execProviderConfig`, that command must be available in the Argo CD image. See [BYOI (Build Your Own Image)](custom_tools.md#byoi-build-your-own-image).
+Note that if you specify a command to run under `execProviderConfig`, that command must be available in the Argo CD image. See [BYOI (Build Your Own Image)](custom_tools.md#byoi-build-your-own-image).
Cluster secret example:
@@ -791,7 +816,7 @@ The above role is granted cluster admin permissions via `AmazonEKSClusterAdminPo
assume this role is therefore granted the same cluster admin permissions when it generates an API token when adding the
associated EKS cluster.
-**AWS Auth (Deprecated)**
+**AWS Auth (Depreciated)**
Instead of using Access Entries, you may need to use the depreciated `aws-auth`.
@@ -1199,7 +1224,6 @@ Notes:
* Quote globs in your YAML to avoid parsing errors.
* Invalid globs result in the whole rule being ignored.
* If you add a rule that matches existing resources, these will appear in the interface as `OutOfSync`.
-* Some excluded objects may already be in the controller cache. A restart of the controller will be necessary to remove them from the Application View.
## Mask sensitive Annotations on Secrets
diff --git a/docs/operator-manual/feature-maturity.md b/docs/operator-manual/feature-maturity.md
index 84f2677238..7db255b1b0 100644
--- a/docs/operator-manual/feature-maturity.md
+++ b/docs/operator-manual/feature-maturity.md
@@ -17,7 +17,7 @@ to indicate their stability and maturity. These are the statuses of non-stable f
| Feature | Introduced | Status |
|-------------------------------------------|------------|--------|
| [AppSet Progressive Syncs][2] | v2.6.0 | Alpha |
-| [Proxy Extensions][3] | v2.7.0 | Beta |
+| [Proxy Extensions][3] | v2.7.0 | Alpha |
| [Skip Application Reconcile][4] | v2.7.0 | Alpha |
| [AppSets in any Namespace][5] | v2.8.0 | Beta |
| [Cluster Sharding: round-robin][6] | v2.8.0 | Alpha |
diff --git a/docs/operator-manual/health.md b/docs/operator-manual/health.md
index cdaf053ea3..ffce008b1f 100644
--- a/docs/operator-manual/health.md
+++ b/docs/operator-manual/health.md
@@ -118,7 +118,7 @@ specify a wildcard in the resource kind, and anywhere in the resource group, lik
!!!important
Please, note that wildcards are only supported when using the `resource.customizations` key, the `resource.customizations.health._`
- style keys do not work since wildcards (`*`) are not supported in Kubernetes configmap keys.
+style keys do not work since wildcards (`*`) are not supported in Kubernetes configmap keys.
The `obj` is a global variable which contains the resource. The script must return an object with status and optional message field.
The custom health check might return one of the following health statuses:
@@ -168,33 +168,7 @@ To test the implemented custom health checks, run `go test -v ./util/lua/`.
The [PR#1139](https://github.com/argoproj/argo-cd/pull/1139) is an example of Cert Manager CRDs custom health check.
-#### Wildcard Support for Built-in Health Checks
-
-You can use a single health check for multiple resources by using a wildcard in the group or kind directory names.
-
-The `_` character behaves like a `*` wildcard. For example, consider the following directory structure:
-
-```
-argo-cd
-|-- resource_customizations
-| |-- _.group.io # CRD group
-| | |-- _ # Resource kind
-| | | |-- health.lua # Health check
-```
-
-Any resource with a group that ends with `.group.io` will use the health check in `health.lua`.
-
-Wildcard checks are only evaluated if there is no specific check for the resource.
-
-If multiple wildcard checks match, the first one in the directory structure is used.
-
-We use the [doublestar](https://github.com/bmatcuk/doublestar) glob library to match the wildcard checks. We currently
-only treat a path as a wildcard if it contains a `_` character, but this may change in the future.
-
-!!!important "Avoid Massive Scripts"
-
- Avoid writing massive scripts to handle multiple resources. They'll get hard to read and maintain. Instead, just
- duplicate the relevant parts in resource-specific scripts.
+Please note that bundled health checks with wildcards are not supported.
## Overriding Go-Based Health Checks
@@ -267,4 +241,4 @@ metadata:
argocd.argoproj.io/ignore-healthcheck: "true"
```
-By doing this, the health status of the Deployment will not affect the health of its parent Application.
+By doing this, the health status of the Deployment will not affect the health of its parent Application.
\ No newline at end of file
diff --git a/docs/operator-manual/high_availability.md b/docs/operator-manual/high_availability.md
index 1a7f3c21c8..a05edf547d 100644
--- a/docs/operator-manual/high_availability.md
+++ b/docs/operator-manual/high_availability.md
@@ -132,8 +132,8 @@ stringData:
* `ARGOCD_CLUSTER_CACHE_BATCH_EVENTS_PROCESSING` - environment variable that enables the controller to collect events
for Kubernetes resources and process them in a batch. This is useful when the cluster contains a large number of resources,
- and the controller is overwhelmed by the number of events. The default value is `true`. `false` would mean that the controller
- would process events one by one.
+ and the controller is overwhelmed by the number of events. The default value is `false`, which means that the controller
+ processes events one by one.
* `ARGOCD_CLUSTER_CACHE_EVENTS_PROCESSING_INTERVAL` - environment variable controlling the interval for processing events in a batch.
The valid value is in the format of Go time duration string, e.g. `1ms`, `1s`, `1m`, `1h`. The default value is `100ms`.
@@ -189,7 +189,8 @@ Argo CD repo server maintains one repository clone locally and uses it for appli
Argo CD determines if manifest generation might change local files in the local repository clone based on the config management tool and application settings.
If the manifest generation has no side effects then requests are processed in parallel without a performance penalty. The following are known cases that might cause slowness and their workarounds:
- * **Multiple Helm based applications pointing to the same directory in one Git repository:** for historical reasons Argo CD used to generate Helm manifests sequentially. Starting v3.0, Argo CD performs a parallel generation of Helm manifests by default.
+ * **Multiple Helm based applications pointing to the same directory in one Git repository:** for historical reasons Argo CD generates Helm manifests sequentially. To enable parallel generation set `ARGOCD_HELM_ALLOW_CONCURRENCY=true` to `argocd-repo-server` deployment or create `.argocd-allow-concurrency` file.
+ Future versions of Argo CD will enable this by default.
* **Multiple Custom plugin based applications:** avoid creating temporal files during manifest generation and create `.argocd-allow-concurrency` file in the app directory, or use the sidecar plugin option, which processes each application using a temporary copy of the repository.
diff --git a/docs/operator-manual/ingress.md b/docs/operator-manual/ingress.md
index 5037d77203..b3a477252f 100644
--- a/docs/operator-manual/ingress.md
+++ b/docs/operator-manual/ingress.md
@@ -408,7 +408,7 @@ spec:
## AWS Application Load Balancers (ALBs) And Classic ELB (HTTP Mode)
AWS ALBs can be used as an L7 Load Balancer for both UI and gRPC traffic, whereas Classic ELBs and NLBs can be used as L4 Load Balancers for both.
-When using an ALB, you'll want to create a second service for argocd-server. This is necessary because we need to tell the ALB to send the GRPC traffic to a different target group than the UI traffic, since the backend protocol is HTTP2 instead of HTTP1.
+When using an ALB, you'll want to create a second service for argocd-server. This is necessary because we need to tell the ALB to send the GRPC traffic to a different target group then the UI traffic, since the backend protocol is HTTP2 instead of HTTP1.
```yaml
apiVersion: v1
diff --git a/docs/operator-manual/installation.md b/docs/operator-manual/installation.md
index 35e4d6bb07..70494298c1 100644
--- a/docs/operator-manual/installation.md
+++ b/docs/operator-manual/installation.md
@@ -31,10 +31,6 @@ Not recommended for production use. This type of installation is typically used
Argo CD instances for different teams, where each instance will be deploying applications to
external clusters. It will still be possible to deploy to the same cluster (kubernetes.svc.default)
with inputted credentials (i.e. `argocd cluster add --in-cluster --namespace `).
- With the default roles included, you will only be able to deploy Argo CD resources (Applications, ApplicationSets
- and AppProjects) in the same cluster, as it's only supporting the GitOps mode with real deployments being
- done to external clusters.
- You can modify that by defining new roles and binding them to the `argocd-application-controller` service account.
> Note: Argo CD CRDs are not included into [namespace-install.yaml](https://github.com/argoproj/argo-cd/blob/master/manifests/namespace-install.yaml).
> and have to be installed separately. The CRD manifests are located in the [manifests/crds](https://github.com/argoproj/argo-cd/blob/master/manifests/crds) directory.
diff --git a/docs/operator-manual/metrics.md b/docs/operator-manual/metrics.md
index 8a65325ac8..deb6037aab 100644
--- a/docs/operator-manual/metrics.md
+++ b/docs/operator-manual/metrics.md
@@ -5,66 +5,27 @@ Argo CD exposes different sets of Prometheus metrics per server.
## Application Controller Metrics
Metrics about applications. Scraped at the `argocd-metrics:8082/metrics` endpoint.
-| Metric | Type | Description |
-|---------------------------------------------------|:---------:|---------------------------------------------------------------------------------------------------------------------------------------------|
-| `argocd_app_info` | gauge | Information about Applications. It contains labels such as `sync_status` and `health_status` that reflect the application state in Argo CD. |
-| `argocd_app_condition` | gauge | Report Applications conditions. It contains the conditions currently present in the application status. |
-| `argocd_app_k8s_request_total` | counter | Number of Kubernetes requests executed during application reconciliation |
-| `argocd_app_labels` | gauge | Argo Application labels converted to Prometheus labels. Disabled by default. See section below about how to enable it. |
-| `argocd_app_orphaned_resources_count` | gauge | Number of orphaned resources per application. |
-| `argocd_app_reconcile` | histogram | Application reconciliation performance in seconds. |
-| `argocd_app_sync_total` | counter | Counter for application sync history |
-| `argocd_cluster_api_resource_objects` | gauge | Number of k8s resource objects in the cache. |
-| `argocd_cluster_api_resources` | gauge | Number of monitored Kubernetes API resources. |
-| `argocd_cluster_cache_age_seconds` | gauge | Cluster cache age in seconds. |
-| `argocd_cluster_connection_status` | gauge | The k8s cluster current connection status. |
-| `argocd_cluster_events_total` | counter | Number of processes k8s resource events. |
-| `argocd_cluster_info` | gauge | Information about cluster. |
-| `argocd_redis_request_duration` | histogram | Redis requests duration. |
-| `argocd_redis_request_total` | counter | Number of redis requests executed during application reconciliation |
-| `argocd_resource_events_processing` | histogram | Time to process resource events in batch in seconds |
-| `argocd_resource_events_processed_in_batch` | gauge | Number of resource events processed in batch |
-| `argocd_kubectl_exec_pending` | gauge | Number of pending kubectl executions |
-| `argocd_kubectl_exec_total` | counter | Number of kubectl executions |
-| `argocd_kubectl_client_cert_rotation_age_seconds` | gauge | Age of kubectl client certificate rotation. |
-| `argocd_kubectl_request_duration_seconds` | histogram | Latency of kubectl requests. |
-| `argocd_kubectl_dns_resolution_duration_seconds` | histogram | Latency of kubectl resolver. |
-| `argocd_kubectl_request_size_bytes` | histogram | Size of kubectl requests. |
-| `argocd_kubectl_response_size_bytes` | histogram | Size of kubectl responses. |
-| `argocd_kubectl_rate_limiter_duration_seconds` | histogram | Latency of kubectl rate limiter. |
-| `argocd_kubectl_requests_total` | counter | Result of kubectl requests. |
-| `argocd_kubectl_exec_plugin_call_total` | counter | Number of kubectl exec plugin calls. |
-| `argocd_kubectl_request_retries_total` | counter | Number of kubectl request retries. |
-| `argocd_kubectl_transport_cache_entries` | gauge | Number of kubectl transport cache entries. |
-| `argocd_kubectl_transport_create_calls_total` | counter | Number of kubectl transport create calls. |
-
-### Labels
-
-| Label Name | Example Value | Description |
-|--------------------|---------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-| call_status | no_error | Status of the kubectl exec plugin call. Possible values are: no_error, plugin_execution_error, plugin_not_found_error, client_internal_error. |
-| code | 200 | HTTP status code returned by the request or exit code of a command. kubectl metrics produced by client-go use `code` for HTTP responses, while metrics produced by Argo CD use `response_code`. |
-| command | apply | kubectl command executed. Possible values are: apply, auth, create, replace. |
-| dest_server | https://example.com | Destination server for an Application. |
-| failed | false | Indicates if the Redis request failed. Possible values are: true, false. |
-| group | apps | Group name of a Kubernetes resource being monitored. |
-| host | example.com | Hostname of the Kubernetes API to which the request was made. |
-| hostname | argocd-application-controller-0 | Hostname of the Argo CD component that initiated the request to Redis. |
-| initiator | argocd-server | Name of the Argo CD component that initiated the request to Redis. Possible values are: argocd-application-controller, argocd-repo-server, argocd-server. |
-| kind | Deployment | Kind name of a Kubernetes resource being monitored. |
-| method | GET | HTTP method used for the request. Possible values are: GET, DELETE, PATCH, POST, PUT. |
-| name | my-app | Name of an Application. |
-| namespace | default | Namespace of an Application (namespace where the Application CR is located, not the destination namespace). |
-| phase | Succeeded | Phase of a sync operation. Possible values are: Error, Failed, Running, Succeeded, Terminating. |
-| project | my-project | AppProject of an Application. |
-| resource_kind | Pod | Kind of Kubernetes resource being synced. |
-| resource_namespace | default | Namespace of Kubernetes resource being synced. |
-| response_code | 404 | HTTP response code from the server. |
-| result | hit | Result of an attempt to get a transport from the kubectl (client-go) transport cache. Possible values are: hit, miss, unreachable. |
-| server | https://example.com | Server where the operation is performed. |
-| verb | List | Kubernetes API verb used in the request. Possible values are: Get, Watch, List, Create, Delete, Patch, Update. |
-
-### Metrics Cache Expiration
+| Metric | Type | Description |
+|--------|:----:|-------------|
+| `argocd_app_info` | gauge | Information about Applications. It contains labels such as `sync_status` and `health_status` that reflect the application state in Argo CD. |
+| `argocd_app_condition` | gauge | Report Applications conditions. It contains the conditions currently present in the application status. |
+| `argocd_app_k8s_request_total` | counter | Number of Kubernetes requests executed during application reconciliation |
+| `argocd_app_labels` | gauge | Argo Application labels converted to Prometheus labels. Disabled by default. See section below about how to enable it. |
+| `argocd_app_orphaned_resources_count` | gauge | Number of orphaned resources per application. |
+| `argocd_app_reconcile` | histogram | Application reconciliation performance in seconds. |
+| `argocd_app_sync_total` | counter | Counter for application sync history |
+| `argocd_cluster_api_resource_objects` | gauge | Number of k8s resource objects in the cache. |
+| `argocd_cluster_api_resources` | gauge | Number of monitored Kubernetes API resources. |
+| `argocd_cluster_cache_age_seconds` | gauge | Cluster cache age in seconds. |
+| `argocd_cluster_connection_status` | gauge | The k8s cluster current connection status. |
+| `argocd_cluster_events_total` | counter | Number of processes k8s resource events. |
+| `argocd_cluster_info` | gauge | Information about cluster. |
+| `argocd_kubectl_exec_pending` | gauge | Number of pending kubectl executions |
+| `argocd_kubectl_exec_total` | counter | Number of kubectl executions |
+| `argocd_redis_request_duration` | histogram | Redis requests duration. |
+| `argocd_redis_request_total` | counter | Number of redis requests executed during application reconciliation |
+| `argocd_resource_events_processing` | histogram | Time to process resource events in batch in seconds |
+| `argocd_resource_events_processed_in_batch` | gauge | Number of resource events processed in batch |
If you use Argo CD with many application and project creation and deletion,
the metrics page will keep in cache your application and project's history.
@@ -73,6 +34,8 @@ to deleted resources, you can schedule a metrics reset to clean the
history with an application controller flag. Example:
`--metrics-cache-expiration="24h0m0s"`.
+
+
### Exposing Application labels as Prometheus metrics
There are use-cases where Argo CD Applications contain labels that are desired to be exposed as Prometheus metrics.
@@ -130,105 +93,30 @@ The example below will expose the Argo CD Application condition `OrphanedResourc
The Application Set controller exposes the following metrics for application sets.
-| Metric | Type | Description |
-|---------------------------------------------------|:---------:|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-| `argocd_appset_info` | gauge | Information about Application Sets. It contains labels for the name and namespace of an application set as well as `Resource_update_status` that reflects the `ResourcesUpToDate` property |
-| `argocd_appset_reconcile` | histogram | Application reconciliation performance in seconds. It contains labels for the name and namespace of an applicationset |
-| `argocd_appset_labels` | gauge | Applicationset labels translated to Prometheus labels. Disabled by default |
-| `argocd_appset_owned_applications` | gauge | Number of applications owned by the applicationset. It contains labels for the name and namespace of an applicationset. |
-| `argocd_kubectl_client_cert_rotation_age_seconds` | gauge | Age of kubectl client certificate rotation. |
-| `argocd_kubectl_request_duration_seconds` | histogram | Latency of kubectl requests. |
-| `argocd_kubectl_dns_resolution_duration_seconds` | histogram | Latency of kubectl resolver. |
-| `argocd_kubectl_request_size_bytes` | histogram | Size of kubectl requests. |
-| `argocd_kubectl_response_size_bytes` | histogram | Size of kubectl responses. |
-| `argocd_kubectl_rate_limiter_duration_seconds` | histogram | Latency of kubectl rate limiter. |
-| `argocd_kubectl_requests_total` | counter | Result of kubectl requests. |
-| `argocd_kubectl_exec_plugin_call_total` | counter | Number of kubectl exec plugin calls. |
-| `argocd_kubectl_request_retries_total` | counter | Number of kubectl request retries. |
-| `argocd_kubectl_transport_cache_entries` | gauge | Number of kubectl transport cache entries. |
-| `argocd_kubectl_transport_create_calls_total` | counter | Number of kubectl transport create calls. |
+| Metric | Type | Description |
+|--------|:----:|-------------|
+| `argocd_appset_info` | gauge | Information about Application Sets. It contains labels for the name and namespace of an application set as well as `Resource_update_status` that reflects the `ResourcesUpToDate` property |
+| `argocd_appset_reconcile` | histogram | Application reconciliation performance in seconds. It contains labels for the name and namespace of an applicationset |
+| `argocd_appset_labels` | gauge | Applicationset labels translated to Prometheus labels. Disabled by default |
+| `argocd_appset_owned_applications` | gauge | Number of applications owned by the applicationset. It contains labels for the name and namespace of an applicationset. |
Similar to the same metric in application controller (`argocd_app_labels`) the metric `argocd_appset_labels` is disabled by default. You can enable it by providing the `–metrics-applicationset-labels` argument to the applicationset controller.
Once enabled it works exactly the same as application controller metrics (label_ appended to normalized label name).
Available labels include Name, Namespace + all labels enabled by the command line options and their value (exactly like application controller metrics described in the previous section).
-### Labels
-
-| Label Name | Example Value | Description |
-|--------------------|---------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------|
-| call_status | no_error | Status of the kubectl exec plugin call. Possible values are: no_error, plugin_execution_error, plugin_not_found_error, client_internal_error. |
-| code | 200 | HTTP status code returned by the request or exit code of a command. |
-| host | example.com | Hostname of the Kubernetes API to which the request was made. |
-| method | GET | HTTP method used for the request. Possible values are: GET, DELETE, PATCH, POST, PUT. |
-| name | my-app | Name of an ApplicationSet. |
-| namespace | default | Namespace of an ApplicationSet (namespace where the ApplicationSet CR is located, not the destination namespace). |
-| result | hit | Result of an attempt to get a transport from the kubectl (client-go) transport cache. Possible values are: hit, miss, unreachable. |
-| verb | List | Kubernetes API verb used in the request. Possible values are: Get, Watch, List, Create, Delete, Patch, Update. |
-
-### Exposing Cluster labels as Prometheus metrics
-
-As the Cluster labels are specific to each company, this feature is disabled by default. To enable it, add the
-`--metrics-cluster-labels` flag to the Argo CD application controller.
-
-The example below will expose the Argo CD Application labels `team-name` and `environment` to Prometheus:
-
- containers:
- - command:
- - argocd-application-controller
- - --metrics-cluster-labels
- - team-name
- - --metrics-cluster-labels
- - environment
-
-In this case, the metric would look like:
-
-```
-# TYPE argocd_app_labels gauge
-argocd_cluster_labels{label_environment="dev",label_team_name="team1",name="cluster1",server="server1"} 1
-argocd_cluster_labels{label_environment="staging",label_team_name="team2",name="cluster2",server="server2"} 1
-argocd_cluster_labels{label_environment="production",label_team_name="team3",name="cluster3",server="server3"} 1
-```
-
## API Server Metrics
Metrics about API Server API request and response activity (request totals, response codes, etc...).
Scraped at the `argocd-server-metrics:8083/metrics` endpoint.
-| Metric | Type | Description |
-|---------------------------------------------------|:---------:|---------------------------------------------------------------------------------------------|
-| `argocd_redis_request_duration` | histogram | Redis requests duration. |
-| `argocd_redis_request_total` | counter | Number of Kubernetes requests executed during application reconciliation. |
-| `grpc_server_handled_total` | counter | Total number of RPCs completed on the server, regardless of success or failure. |
-| `grpc_server_msg_sent_total` | counter | Total number of gRPC stream messages sent by the server. |
-| `argocd_proxy_extension_request_total` | counter | Number of requests sent to the configured proxy extensions. |
+| Metric | Type | Description |
+|--------|:----:|-------------|
+| `argocd_redis_request_duration` | histogram | Redis requests duration. |
+| `argocd_redis_request_total` | counter | Number of Kubernetes requests executed during application reconciliation. |
+| `grpc_server_handled_total` | counter | Total number of RPCs completed on the server, regardless of success or failure. |
+| `grpc_server_msg_sent_total` | counter | Total number of gRPC stream messages sent by the server. |
+| `argocd_proxy_extension_request_total` | counter | Number of requests sent to the configured proxy extensions. |
| `argocd_proxy_extension_request_duration_seconds` | histogram | Request duration in seconds between the Argo CD API server and the proxy extension backend. |
-| `argocd_kubectl_client_cert_rotation_age_seconds` | gauge | Age of kubectl client certificate rotation. |
-| `argocd_kubectl_request_duration_seconds` | histogram | Latency of kubectl requests. |
-| `argocd_kubectl_dns_resolution_duration_seconds` | histogram | Latency of kubectl resolver. |
-| `argocd_kubectl_request_size_bytes` | histogram | Size of kubectl requests. |
-| `argocd_kubectl_response_size_bytes` | histogram | Size of kubectl responses. |
-| `argocd_kubectl_rate_limiter_duration_seconds` | histogram | Latency of kubectl rate limiter. |
-| `argocd_kubectl_requests_total` | counter | Result of kubectl requests. |
-| `argocd_kubectl_exec_plugin_call_total` | counter | Number of kubectl exec plugin calls. |
-| `argocd_kubectl_request_retries_total` | counter | Number of kubectl request retries. |
-| `argocd_kubectl_transport_cache_entries` | gauge | Number of kubectl transport cache entries. |
-| `argocd_kubectl_transport_create_calls_total` | counter | Number of kubectl transport create calls. |
-
-### Labels
-
-| Label Name | Example Value | Description |
-|--------------------|---------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-| call_status | no_error | Status of the kubectl exec plugin call. Possible values are: no_error, plugin_execution_error, plugin_not_found_error, client_internal_error. |
-| code | 200 | HTTP status code returned by the request or exit code of a command. kubectl metrics produced by client-go use `code` for HTTP responses, while metrics produced by Argo CD proxy extensions use `status`. |
-| extension | metrics | Name of the proxy extension being called. |
-| failed | false | Indicates if the Redis request failed. Possible values are: true, false. |
-| host | example.com | Hostname of the Kubernetes API to which the request was made. |
-| initiator | argocd-server | Name of the Argo CD component that initiated the request to Redis. Possible values are: argocd-application-controller, argocd-repo-server, argocd-server. |
-| method | GET | HTTP method used for the request. Possible values are: GET, DELETE, PATCH, POST, PUT. |
-| result | hit | Result of an attempt to get a transport from the kubectl (client-go) transport cache. Possible values are: hit, miss, unreachable. |
-| status | 200 | HTTP response code from the extension. |
-| verb | List | Kubernetes API verb used in the request. Possible values are: Get, Watch, List, Create, Delete, Patch, Update. |
-| version | v2.13.3 | Argo CD version. |
## Repo Server Metrics
Metrics about the Repo Server.
diff --git a/docs/operator-manual/notifications/catalog.md b/docs/operator-manual/notifications/catalog.md
index a5385889f8..d92561f67a 100644
--- a/docs/operator-manual/notifications/catalog.md
+++ b/docs/operator-manual/notifications/catalog.md
@@ -87,7 +87,7 @@ teams:
},
{
"name": {{- if .app.spec.source }} "Repository" {{- else if .app.spec.sources }} "Repositories" {{- end }},
- "value": {{- if .app.spec.source }} ":arrow_heading_up: {{ .app.spec.source.repoURL }}" {{- else if .app.spec.sources }} "{{- range $index, $source := .app.spec.sources }}{{ if $index }}\n{{ end }}:arrow_heading_up: {{ $source.repoURL }}{{- end }}" {{- end }}
+ "value": {{- if .app.spec.source }} ":arrow_heading_up: {{ .app.spec.source.repoURL }}" {{- else if .app.spec.sources }} "{{- range $index, $source := .app.spec.sources }}{{ if $index }}\n{{ end }}:arrow_heading_up: {{ $source.repoURL }}{{- end }}" {{- end }},
},
{
"name": "Revision",
@@ -115,7 +115,7 @@ teams:
"name":"Open Repository",
"targets":[{
"os":"default",
- "uri":{{- if .app.spec.source }} ":arrow_heading_up: {{ .app.spec.source.repoURL }}" {{- else if .app.spec.sources }} "{{- range $index, $source := .app.spec.sources }}{{ if $index }}\n{{ end }}:arrow_heading_up: {{ $source.repoURL }}{{- end }}" {{- end }}
+ "uri":{{- if .app.spec.source }} ":arrow_heading_up: {{ .app.spec.source.repoURL }}" {{- else if .app.spec.sources }} "{{- range $index, $source := .app.spec.sources }}{{ if $index }}\n{{ end }}:arrow_heading_up: {{ $source.repoURL }}{{- end }}" {{- end }},
}]
}]
themeColor: '#000080'
@@ -168,7 +168,7 @@ teams:
},
{
"name": {{- if .app.spec.source }} "Repository" {{- else if .app.spec.sources }} "Repositories" {{- end }},
- "value": {{- if .app.spec.source }} ":arrow_heading_up: {{ .app.spec.source.repoURL }}" {{- else if .app.spec.sources }} "{{- range $index, $source := .app.spec.sources }}{{ if $index }}\n{{ end }}:arrow_heading_up: {{ $source.repoURL }}{{- end }}" {{- end }}
+ "value": {{- if .app.spec.source }} ":arrow_heading_up: {{ .app.spec.source.repoURL }}" {{- else if .app.spec.sources }} "{{- range $index, $source := .app.spec.sources }}{{ if $index }}\n{{ end }}:arrow_heading_up: {{ $source.repoURL }}{{- end }}" {{- end }},
}
{{range $index, $c := .app.status.conditions}}
,
@@ -192,7 +192,7 @@ teams:
"name":"Open Repository",
"targets":[{
"os":"default",
- "uri":{{- if .app.spec.source }} ":arrow_heading_up: {{ .app.spec.source.repoURL }}" {{- else if .app.spec.sources }} "{{- range $index, $source := .app.spec.sources }}{{ if $index }}\n{{ end }}:arrow_heading_up: {{ $source.repoURL }}{{- end }}" {{- end }}
+ "uri":{{- if .app.spec.source }} ":arrow_heading_up: {{ .app.spec.source.repoURL }}" {{- else if .app.spec.sources }} "{{- range $index, $source := .app.spec.sources }}{{ if $index }}\n{{ end }}:arrow_heading_up: {{ $source.repoURL }}{{- end }}" {{- end }},
}]
}]
themeColor: '#FF0000'
@@ -249,7 +249,7 @@ teams:
},
{
"name": {{- if .app.spec.source }} "Repository" {{- else if .app.spec.sources }} "Repositories" {{- end }},
- "value": {{- if .app.spec.source }} ":arrow_heading_up: {{ .app.spec.source.repoURL }}" {{- else if .app.spec.sources }} "{{- range $index, $source := .app.spec.sources }}{{ if $index }}\n{{ end }}:arrow_heading_up: {{ $source.repoURL }}{{- end }}" {{- end }}
+ "value": {{- if .app.spec.source }} ":arrow_heading_up: {{ .app.spec.source.repoURL }}" {{- else if .app.spec.sources }} "{{- range $index, $source := .app.spec.sources }}{{ if $index }}\n{{ end }}:arrow_heading_up: {{ $source.repoURL }}{{- end }}" {{- end }},
}
{{range $index, $c := .app.status.conditions}}
,
@@ -273,7 +273,7 @@ teams:
"name":"Open Repository",
"targets":[{
"os":"default",
- "uri":{{- if .app.spec.source }} ":arrow_heading_up: {{ .app.spec.source.repoURL }}" {{- else if .app.spec.sources }} "{{- range $index, $source := .app.spec.sources }}{{ if $index }}\n{{ end }}:arrow_heading_up: {{ $source.repoURL }}{{- end }}" {{- end }}
+ "uri":{{- if .app.spec.source }} ":arrow_heading_up: {{ .app.spec.source.repoURL }}" {{- else if .app.spec.sources }} "{{- range $index, $source := .app.spec.sources }}{{ if $index }}\n{{ end }}:arrow_heading_up: {{ $source.repoURL }}{{- end }}" {{- end }},
}]
}]
themeColor: '#FF0000'
@@ -330,7 +330,7 @@ teams:
},
{
"name": {{- if .app.spec.source }} "Repository" {{- else if .app.spec.sources }} "Repositories" {{- end }},
- "value": {{- if .app.spec.source }} ":arrow_heading_up: {{ .app.spec.source.repoURL }}" {{- else if .app.spec.sources }} "{{- range $index, $source := .app.spec.sources }}{{ if $index }}\n{{ end }}:arrow_heading_up: {{ $source.repoURL }}{{- end }}" {{- end }}
+ "value": {{- if .app.spec.source }} ":arrow_heading_up: {{ .app.spec.source.repoURL }}" {{- else if .app.spec.sources }} "{{- range $index, $source := .app.spec.sources }}{{ if $index }}\n{{ end }}:arrow_heading_up: {{ $source.repoURL }}{{- end }}" {{- end }},
}
{{range $index, $c := .app.status.conditions}}
,
@@ -354,7 +354,7 @@ teams:
"name":"Open Repository",
"targets":[{
"os":"default",
- "uri":{{- if .app.spec.source }} ":arrow_heading_up: {{ .app.spec.source.repoURL }}" {{- else if .app.spec.sources }} "{{- range $index, $source := .app.spec.sources }}{{ if $index }}\n{{ end }}:arrow_heading_up: {{ $source.repoURL }}{{- end }}" {{- end }}
+ "uri":{{- if .app.spec.source }} ":arrow_heading_up: {{ .app.spec.source.repoURL }}" {{- else if .app.spec.sources }} "{{- range $index, $source := .app.spec.sources }}{{ if $index }}\n{{ end }}:arrow_heading_up: {{ $source.repoURL }}{{- end }}" {{- end }},
}]
}]
title: Start syncing application {{.app.metadata.name}}.
@@ -411,7 +411,7 @@ teams:
},
{
"name": {{- if .app.spec.source }} "Repository" {{- else if .app.spec.sources }} "Repositories" {{- end }},
- "value": {{- if .app.spec.source }} ":arrow_heading_up: {{ .app.spec.source.repoURL }}" {{- else if .app.spec.sources }} "{{- range $index, $source := .app.spec.sources }}{{ if $index }}\n{{ end }}:arrow_heading_up: {{ $source.repoURL }}{{- end }}" {{- end }}
+ "value": {{- if .app.spec.source }} ":arrow_heading_up: {{ .app.spec.source.repoURL }}" {{- else if .app.spec.sources }} "{{- range $index, $source := .app.spec.sources }}{{ if $index }}\n{{ end }}:arrow_heading_up: {{ $source.repoURL }}{{- end }}" {{- end }},
}
{{range $index, $c := .app.status.conditions}}
,
@@ -435,7 +435,7 @@ teams:
"name":"Open Repository",
"targets":[{
"os":"default",
- "uri":{{- if .app.spec.source }} ":arrow_heading_up: {{ .app.spec.source.repoURL }}" {{- else if .app.spec.sources }} "{{- range $index, $source := .app.spec.sources }}{{ if $index }}\n{{ end }}:arrow_heading_up: {{ $source.repoURL }}{{- end }}" {{- end }}
+ "uri":{{- if .app.spec.source }} ":arrow_heading_up: {{ .app.spec.source.repoURL }}" {{- else if .app.spec.sources }} "{{- range $index, $source := .app.spec.sources }}{{ if $index }}\n{{ end }}:arrow_heading_up: {{ $source.repoURL }}{{- end }}" {{- end }},
}]
}]
title: Application {{.app.metadata.name}} sync status is 'Unknown'
@@ -491,7 +491,7 @@ teams:
},
{
"name": {{- if .app.spec.source }} "Repository" {{- else if .app.spec.sources }} "Repositories" {{- end }},
- "value": {{- if .app.spec.source }} ":arrow_heading_up: {{ .app.spec.source.repoURL }}" {{- else if .app.spec.sources }} "{{- range $index, $source := .app.spec.sources }}{{ if $index }}\n{{ end }}:arrow_heading_up: {{ $source.repoURL }}{{- end }}" {{- end }}
+ "value": {{- if .app.spec.source }} ":arrow_heading_up: {{ .app.spec.source.repoURL }}" {{- else if .app.spec.sources }} "{{- range $index, $source := .app.spec.sources }}{{ if $index }}\n{{ end }}:arrow_heading_up: {{ $source.repoURL }}{{- end }}" {{- end }},
}
{{range $index, $c := .app.status.conditions}}
,
@@ -515,7 +515,7 @@ teams:
"name":"Open Repository",
"targets":[{
"os":"default",
- "uri":{{- if .app.spec.source }} ":arrow_heading_up: {{ .app.spec.source.repoURL }}" {{- else if .app.spec.sources }} "{{- range $index, $source := .app.spec.sources }}{{ if $index }}\n{{ end }}:arrow_heading_up: {{ $source.repoURL }}{{- end }}" {{- end }}
+ "uri":{{- if .app.spec.source }} ":arrow_heading_up: {{ .app.spec.source.repoURL }}" {{- else if .app.spec.sources }} "{{- range $index, $source := .app.spec.sources }}{{ if $index }}\n{{ end }}:arrow_heading_up: {{ $source.repoURL }}{{- end }}" {{- end }},
}]
}]
themeColor: '#000080'
diff --git a/docs/operator-manual/notifications/examples.md b/docs/operator-manual/notifications/examples.md
deleted file mode 100644
index b86a0a2b9a..0000000000
--- a/docs/operator-manual/notifications/examples.md
+++ /dev/null
@@ -1,133 +0,0 @@
-Here you can find some examples of what you can do with the notifications service in Argo CD.
-
-## Getting notified when a sync occurs and understanding how your resources changed
-
-With Argo CD you can build a notification system that tells you when a sync occurred and what it changed.
-To get notified via webhook when a sync occurs you can add the following trigger:
-
-```yaml
-apiVersion: v1
-kind: ConfigMap
-metadata:
- name: argocd-notifications-cm
-data:
- service.webhook.on-deployed-webhook: |
- url:
- headers:
- - name: "Content-Type"
- value: "application/json"
-
- template.on-deployed-template: |
- webhook:
- on-deployed-webhook:
- method: POST
- body: |
- {{toJson .app.status.operationState.syncResult}}
-
-
- trigger.on-deployed-trigger: |
- when: app.status.operationState.phase in ['Succeeded'] and app.status.health.status == 'Healthy'
- oncePer: app.status.sync.revision
- send: [on-deployed-template]
-```
-
-This, as explained in the [triggers section](triggers/#avoid-sending-same-notification-too-often), will generate a notification when the app is synced and healthy. We then need to create a subscription for the webhook integration:
-
-```yaml
-apiVersion: argoproj.io/v1alpha1
-kind: Application
-metadata:
- annotations:
- notifications.argoproj.io/subscribe.on-deployed-trigger.on-deployed-webhook: ""
-```
-
-You can test that this works and see how the response looks by adding any webhook site and syncing our application. Here you can see that we receive a list of resources, with a message and some properties of them. For example:
-
-```json
-{
- "resources": [
- {
- "group": "apps",
- "hookPhase": "Running",
- # The images array follows the same order as in the resource yaml
- "images": [
- "nginx:1.27.1"
- ],
- "kind": "Deployment",
- "message": "deployment.apps/test configured",
- "name": "test",
- "namespace": "argocd",
- "status": "Synced",
- "syncPhase": "Sync",
- "version": "v1"
- },
- {
- "group": "autoscaling",
- "hookPhase": "Running",
- "kind": "HorizontalPodAutoscaler",
- "message": "horizontalpodautoscaler.autoscaling/test-hpa unchanged",
- "name": "test-hpa",
- "namespace": "argocd",
- "status": "Synced",
- "syncPhase": "Sync",
- "version": "v2"
- }
- ],
- "revision": "f3937462080c6946ff5ec4b5fa393e7c22388e4c",
- ...
-}
-```
-
-We can leverage this information to know:
-
-1. What resources have changed (not valid for Server Side Apply)
-2. How they changed
-
-To understand what resources changed we can check the message associated with each resource. Those that say that are unchanged were not affected during the sync operation. With the list of changed resources, we can understand how they changed by looking into the images array.
-
-With this information you can, for example:
-
-1. Monitor the version of your image being deployed
-2. Rollback deployments with images that are known to be faulty within your organisation
-3. Detect unexpected image changes: by monitoring the images array in the webhook payload, you can verify that only expected container images are being deployed
-
-This helps you build a notification system that allows you to understand the status of your deployments in a more advanced manner.
-
-## Send the list of images to Slack
-
-Here we can use a similar setup as the one above, but change the receiver to be Slack:
-
-```yaml
-apiVersion: v1
-kind: ConfigMap
-metadata:
- name: argocd-notifications-cm
-data:
-data:
- service.slack: |
- token:
-
- template.on-deployed-template: |
- slack:
- message: |
- *Deployment Notification*
- *Application:* `{{.app.metadata.name}}`
- *Namespace:* `{{.app.spec.destination.namespace}}`
- *Revision:* `{{.app.status.sync.revision}}`
- *Deployed Images:*
- {{- range $resource := .app.status.operationState.syncResult.resources -}}
- {{- range $image := $resource.images -}}
- - "{{$image}}"
- {{- end }}
- {{- end }}
- trigger.on-deployed-trigger: |
- when: app.status.operationState.phase in ['Succeeded'] and app.status.health.status == 'Healthy'
- oncePer: app.status.sync.revision
- send: [on-deployed-template]
-```
-
-Now, with the setup above, a sync will send the list of images to your Slack application. For more information about integratin with Slack, see the [Slack integration guide](/operator-manual/notifications/services/slack/).
-
-### Deduplicating images
-
-Although the field in `syncResult.resources` contains only resources declared by the user in the GitOps repository you might end up with duplicated images depending on your setup. To avoid having duplicated images, you need to create an external webhook receiver that deduplicates the images, and then send the message to Slack.
diff --git a/docs/operator-manual/notifications/index.md b/docs/operator-manual/notifications/index.md
index 13e7170c47..002f67249c 100644
--- a/docs/operator-manual/notifications/index.md
+++ b/docs/operator-manual/notifications/index.md
@@ -112,4 +112,4 @@ metadata:
When the same notification service and trigger are defined in controller level configuration and application level configuration,
both notifications will be sent according to its own configuration.
-[Defining and using secrets within notification templates](templates/#defining-and-using-secrets-within-notification-templates) function is not available when flag `--self-service-notification-enable` is on.
+[Defining and using secrets within notification templates](templates.md/#defining-and-using-secrets-within-notification-templates) function is not available when flag `--self-service-notification-enable` is on.
diff --git a/docs/operator-manual/notifications/services/github.md b/docs/operator-manual/notifications/services/github.md
index 1dc72d83e1..4cd2523908 100755
--- a/docs/operator-manual/notifications/services/github.md
+++ b/docs/operator-manual/notifications/services/github.md
@@ -84,19 +84,6 @@ template.app-deployed: |
content: |
Application {{.app.metadata.name}} is now running new version of deployments manifests.
See more here: {{.context.argocdUrl}}/applications/{{.app.metadata.name}}?operation=true
- checkRun:
- name: "continuous-delivery/{{.app.metadata.name}}"
- details_url: "{{.context.argocdUrl}}/applications/{{.app.metadata.name}}?operation=true"
- status: completed
- conclusion: success
- started_at: "YYYY-MM-DDTHH:MM:SSZ"
- completed_at: "YYYY-MM-DDTHH:MM:SSZ"
- output:
- title: "Deployment of {{.app.metadata.name}} on ArgoCD"
- summary: "Application {{.app.metadata.name}} is now running new version of deployments manifests."
- text: |
- Application {{.app.metadata.name}} is now running new version of deployments manifests.
- See more here: {{.context.argocdUrl}}/applications/{{.app.metadata.name}}?operation=true
```
**Notes**:
diff --git a/docs/operator-manual/project.yaml b/docs/operator-manual/project.yaml
index ec8dd4d654..c4d93f5362 100644
--- a/docs/operator-manual/project.yaml
+++ b/docs/operator-manual/project.yaml
@@ -14,16 +14,12 @@ spec:
sourceRepos:
- '*'
- # Only permit applications to deploy to the 'guestbook' namespace or any namespace starting with 'guestbook-' in the same cluster
+ # Only permit applications to deploy to the guestbook namespace in the same cluster
# Destination clusters can be identified by 'server', 'name', or both.
destinations:
- namespace: guestbook
server: https://kubernetes.default.svc
name: in-cluster
- # Destinations also allow wildcard globbing
- - namespace: guestbook-*
- server: https://kubernetes.default.svc
- name: in-cluster
# Deny all cluster-scoped resources from being created, except for Namespace
clusterResourceWhitelist:
diff --git a/docs/operator-manual/rbac.md b/docs/operator-manual/rbac.md
index 8648448f49..eb45f92bec 100644
--- a/docs/operator-manual/rbac.md
+++ b/docs/operator-manual/rbac.md
@@ -42,7 +42,7 @@ The anonymous access to Argo CD can be enabled using the `users.anonymous.enable
## RBAC Model Structure
-The model syntax is based on [Casbin](https://casbin.org/docs/overview) (an open source ACL/ACLs). There are two different types of syntax: one for assigning policies, and another one for assigning users to internal roles.
+The model syntax is based on [Casbin](https://casbin.org/docs/overview). There are two different types of syntax: one for assigning policies, and another one for assigning users to internal roles.
**Group**: Allows to assign authenticated users/groups to internal roles.
@@ -114,8 +114,8 @@ The `applications` resource is an [Application-Specific Policy](#application-spe
#### Fine-grained Permissions for `update`/`delete` action
-The `update` and `delete` actions, when granted on an application, will allow the user to perform the operation on the application itself,
-but not on its resources.
+The `update` and `delete` actions, when granted on an application, will allow the user to perform the operation on the application itself **and** all of its resources.
+It can be desirable to only allow `update` or `delete` on specific resources within an application.
To do so, when the action if performed on an application's resource, the `` will have the `////` format.
@@ -148,30 +148,28 @@ p, example-user, applications, delete, default/prod-app, deny
p, example-user, applications, delete/*/Pod/*/*, default/prod-app, allow
```
-If we want to explicitly allow updates to the application, but deny updates to any sub-resources:
+!!! note "Disable Application permission Inheritance"
-```csv
-p, example-user, applications, update, default/prod-app, allow
-p, example-user, applications, update/*, default/prod-app, deny
-```
-
-!!! note "Preserve Application permission Inheritance (Since v3.0.0)"
-
- Prior to v3, `update` and `delete` actions (without a `/*`) were also evaluated
- on sub-resources.
-
- To preserve this behavior, you can set the config value
- `server.rbac.disableApplicationFineGrainedRBACInheritance` to `false` in
- the Argo CD ConfigMap `argocd-cm`.
-
- When disabled, it is not possible to deny fine-grained permissions for a sub-resource
- if the action was **explicitly allowed on the application**.
- For instance, the following policies will **allow** a user to delete the Pod and any
- other resources in the application:
+ By default, it is not possible to deny fine-grained permissions for a sub-resource if the action was **explicitly allowed on the application**.
+ For instance, the following policies will **allow** a user to delete the Pod and any other resources in the application:
```csv
p, example-user, applications, delete, default/prod-app, allow
- p, example-user, applications, delete/*/Pod/*, default/prod-app, deny
+ p, example-user, applications, delete/*/Pod/*/*, default/prod-app, deny
+ ```
+
+ To change this behavior, you can set the config value
+ `server.rbac.disableApplicationFineGrainedRBACInheritance` to `true` in
+ the Argo CD ConfigMap `argocd-cm`.
+
+ When inheritance is disabled, it is now possible to deny fine-grained permissions for a sub-resource
+ if the action was **explicitly allowed on the application**.
+
+ For instance, if we want to explicitly allow updates to the application, but deny updates to any sub-resources:
+
+ ```csv
+ p, example-user, applications, update, default/prod-app, allow
+ p, example-user, applications, update/*, default/prod-app, deny
```
#### The `action` action
diff --git a/docs/operator-manual/reconcile.md b/docs/operator-manual/reconcile.md
index 699b4335ab..21394af5c7 100644
--- a/docs/operator-manual/reconcile.md
+++ b/docs/operator-manual/reconcile.md
@@ -4,7 +4,7 @@ By default, an Argo CD Application is refreshed every time a resource that belon
Kubernetes controllers often update the resources they watch periodically, causing continuous reconcile operation on the Application
and a high CPU usage on the `argocd-application-controller`. Argo CD allows you to optionally ignore resource updates on specific fields
-for [tracked resources](../user-guide/resource_tracking.md).
+for [tracked resources](../user-guide/resource_tracking.md).
For untracked resources, you can [use the argocd.argoproj.io/ignore-resource-updates annotations](#ignoring-updates-for-untracked-resources)
When a resource update is ignored, if the resource's [health status](./health.md) does not change, the Application that this resource belongs to will not be reconciled.
@@ -20,18 +20,17 @@ metadata:
name: argocd-cm
namespace: argocd
data:
- resource.ignoreResourceUpdatesEnabled: 'false'
+ resource.ignoreResourceUpdatesEnabled: "false"
```
-Argo CD allows ignoring resource updates at a specific JSON path, using [RFC6902 JSON patches](https://tools.ietf.org/html/rfc6902) and [JQ path expressions](). It can be configured for a specified group and kind
+Argo CD allows ignoring resource updates at a specific JSON path, using [RFC6902 JSON patches](https://tools.ietf.org/html/rfc6902) and [JQ path expressions](https://stedolan.github.io/jq/manual/#path(path_expression)). It can be configured for a specified group and kind
in `resource.customizations` key of the `argocd-cm` ConfigMap.
Following is an example of a customization which ignores the `refreshTime` status field of an [`ExternalSecret`](https://external-secrets.io/main/api/externalsecret/) resource:
```yaml
data:
- resource.customizations.ignoreResourceUpdates.external-secrets.io_ExternalSecret:
- |
+ resource.customizations.ignoreResourceUpdates.external-secrets.io_ExternalSecret: |
jsonPointers:
- /status/refreshTime
# JQ equivalent of the above:
@@ -50,9 +49,8 @@ data:
### Using ignoreDifferences to ignore reconcile
-By default, the existing system-level `ignoreDifferences` customizations will be added to ignore resource updates as well. This helps reduce config management by preventing you to copy all existing ignore differences configurations.
-
-To disable this behavior, the `ignoreDifferencesOnResourceUpdates` setting can be disabled:
+It is possible to use existing system-level `ignoreDifferences` customizations to ignore resource updates as well. Instead of copying all configurations,
+the `ignoreDifferencesOnResourceUpdates` setting can be used to add all ignored differences as ignored resource updates:
```yaml
apiVersion: v1
@@ -61,7 +59,7 @@ metadata:
name: argocd-cm
data:
resource.compareoptions: |
- ignoreDifferencesOnResourceUpdates: false
+ ignoreDifferencesOnResourceUpdates: true
```
## Default Configuration
@@ -74,11 +72,11 @@ The application controller logs when a resource change triggers a refresh. You c
high-churn resource kinds and then inspect those resources to find which fields to ignore.
To find these logs, search for `"Requesting app refresh caused by object update"`. The logs include structured
-fields for `api-version` and `kind`. Counting the number of refreshes triggered, by api-version/kind should
+fields for `api-version` and `kind`. Counting the number of refreshes triggered, by api-version/kind should
reveal the high-churn resource kinds.
-!!!note
-These logs are at the `debug` level. Configure the application-controller's log level to `debug`.
+!!!note
+ These logs are at the `debug` level. Configure the application-controller's log level to `debug`.
Once you have identified some resources which change often, you can try to determine which fields are changing. Here is
one approach:
@@ -100,7 +98,7 @@ Whenever Argo CD skips a refresh due to an ignored resource update, the controll
Search the application-controller logs for this line to confirm that your resource ignore rules are being applied.
!!!note
-These logs are at the `debug` level. Configure the application-controller's log level to `debug`.
+ These logs are at the `debug` level. Configure the application-controller's log level to `debug`.
## Examples
@@ -142,37 +140,36 @@ metadata:
name: hello
namespace: test-cronjob
spec:
- schedule: '* * * * *'
+ schedule: "* * * * *"
jobTemplate:
metadata:
annotations:
- argocd.argoproj.io/ignore-resource-updates: 'true'
+ argocd.argoproj.io/ignore-resource-updates: "true"
spec:
template:
metadata:
annotations:
- argocd.argoproj.io/ignore-resource-updates: 'true'
+ argocd.argoproj.io/ignore-resource-updates: "true"
spec:
containers:
- - name: hello
- image: busybox:1.28
- imagePullPolicy: IfNotPresent
- command:
- - /bin/sh
- - -c
- - date; echo Hello from the Kubernetes cluster
+ - name: hello
+ image: busybox:1.28
+ imagePullPolicy: IfNotPresent
+ command:
+ - /bin/sh
+ - -c
+ - date; echo Hello from the Kubernetes cluster
restartPolicy: OnFailure
```
The resource updates will be ignored based on your the `ignoreResourceUpdates` configuration in the `argocd-cm` configMap:
`argocd-cm`:
-
```yaml
resource.customizations.ignoreResourceUpdates.batch_Job: |
- jsonPointers:
- - /status
+ jsonPointers:
+ - /status
resource.customizations.ignoreResourceUpdates.Pod: |
- jsonPointers:
- - /status
+ jsonPointers:
+ - /status
```
diff --git a/docs/operator-manual/resource_actions.md b/docs/operator-manual/resource_actions.md
index a76225316d..8de2984ce0 100644
--- a/docs/operator-manual/resource_actions.md
+++ b/docs/operator-manual/resource_actions.md
@@ -203,21 +203,3 @@ resource.customizations.actions.ConfigMap: |
result[2] = impactedResource2
return result
```
-
-### Action Icons and Display Names
-
-By default, an action will appear in the UI by the name specified in the `actions` key, and it will have no icon. You
-can customize the display name and icon of an action by adding the `iconClass` and `displayName` keys to the action
-definition.
-
-The icon class name is the name of a FontAwesome icon from [the set of free icons](https://fontawesome.com/search?ic=free).
-The `fa-fw` class ensures that the icon is displayed with a fixed width, to avoid alignment issues with other icons.
-
-```lua
-local actions = {}
-actions["create-workflow"] = {
- ["iconClass"] = "fa fa-fw fa-play",
- ["displayName"] = "Create Workflow"
-}
-return actions
-```
diff --git a/docs/operator-manual/resource_actions_builtin.md b/docs/operator-manual/resource_actions_builtin.md
index c3ebbff5d1..9708dcbd1e 100644
--- a/docs/operator-manual/resource_actions_builtin.md
+++ b/docs/operator-manual/resource_actions_builtin.md
@@ -2,18 +2,14 @@
- [apps/Deployment/pause](https://github.com/argoproj/argo-cd/blob/master/resource_customizations/apps/Deployment/actions/pause/action.lua)
- [apps/Deployment/restart](https://github.com/argoproj/argo-cd/blob/master/resource_customizations/apps/Deployment/actions/restart/action.lua)
- [apps/Deployment/resume](https://github.com/argoproj/argo-cd/blob/master/resource_customizations/apps/Deployment/actions/resume/action.lua)
-- [apps/Deployment/scale](https://github.com/argoproj/argo-cd/blob/master/resource_customizations/apps/Deployment/actions/scale/action.lua)
- [apps/StatefulSet/restart](https://github.com/argoproj/argo-cd/blob/master/resource_customizations/apps/StatefulSet/actions/restart/action.lua)
-- [apps/StatefulSet/scale](https://github.com/argoproj/argo-cd/blob/master/resource_customizations/apps/StatefulSet/actions/scale/action.lua)
- [argoproj.io/AnalysisRun/terminate](https://github.com/argoproj/argo-cd/blob/master/resource_customizations/argoproj.io/AnalysisRun/actions/terminate/action.lua)
- [argoproj.io/CronWorkflow/create-workflow](https://github.com/argoproj/argo-cd/blob/master/resource_customizations/argoproj.io/CronWorkflow/actions/create-workflow/action.lua)
- [argoproj.io/Rollout/abort](https://github.com/argoproj/argo-cd/blob/master/resource_customizations/argoproj.io/Rollout/actions/abort/action.lua)
-- [argoproj.io/Rollout/pause](https://github.com/argoproj/argo-cd/blob/master/resource_customizations/argoproj.io/Rollout/actions/pause/action.lua)
- [argoproj.io/Rollout/promote-full](https://github.com/argoproj/argo-cd/blob/master/resource_customizations/argoproj.io/Rollout/actions/promote-full/action.lua)
- [argoproj.io/Rollout/restart](https://github.com/argoproj/argo-cd/blob/master/resource_customizations/argoproj.io/Rollout/actions/restart/action.lua)
- [argoproj.io/Rollout/resume](https://github.com/argoproj/argo-cd/blob/master/resource_customizations/argoproj.io/Rollout/actions/resume/action.lua)
- [argoproj.io/Rollout/retry](https://github.com/argoproj/argo-cd/blob/master/resource_customizations/argoproj.io/Rollout/actions/retry/action.lua)
-- [argoproj.io/Rollout/skip-current-step](https://github.com/argoproj/argo-cd/blob/master/resource_customizations/argoproj.io/Rollout/actions/skip-current-step/action.lua)
- [argoproj.io/WorkflowTemplate/create-workflow](https://github.com/argoproj/argo-cd/blob/master/resource_customizations/argoproj.io/WorkflowTemplate/actions/create-workflow/action.lua)
- [batch/CronJob/create-job](https://github.com/argoproj/argo-cd/blob/master/resource_customizations/batch/CronJob/actions/create-job/action.lua)
- [external-secrets.io/ExternalSecret/refresh](https://github.com/argoproj/argo-cd/blob/master/resource_customizations/external-secrets.io/ExternalSecret/actions/refresh/action.lua)
@@ -41,16 +37,10 @@
- [numaflow.numaproj.io/MonoVertex/unpause](https://github.com/argoproj/argo-cd/blob/master/resource_customizations/numaflow.numaproj.io/MonoVertex/actions/unpause/action.lua)
- [numaflow.numaproj.io/Pipeline/pause](https://github.com/argoproj/argo-cd/blob/master/resource_customizations/numaflow.numaproj.io/Pipeline/actions/pause/action.lua)
- [numaflow.numaproj.io/Pipeline/unpause](https://github.com/argoproj/argo-cd/blob/master/resource_customizations/numaflow.numaproj.io/Pipeline/actions/unpause/action.lua)
-- [numaplane.numaproj.io/ISBServiceRollout/disable-force-promote](https://github.com/argoproj/argo-cd/blob/master/resource_customizations/numaplane.numaproj.io/ISBServiceRollout/actions/disable-force-promote/action.lua)
-- [numaplane.numaproj.io/ISBServiceRollout/enable-force-promote](https://github.com/argoproj/argo-cd/blob/master/resource_customizations/numaplane.numaproj.io/ISBServiceRollout/actions/enable-force-promote/action.lua)
-- [numaplane.numaproj.io/MonoVertexRollout/disable-force-promote](https://github.com/argoproj/argo-cd/blob/master/resource_customizations/numaplane.numaproj.io/MonoVertexRollout/actions/disable-force-promote/action.lua)
-- [numaplane.numaproj.io/MonoVertexRollout/enable-force-promote](https://github.com/argoproj/argo-cd/blob/master/resource_customizations/numaplane.numaproj.io/MonoVertexRollout/actions/enable-force-promote/action.lua)
- [numaplane.numaproj.io/MonoVertexRollout/pause](https://github.com/argoproj/argo-cd/blob/master/resource_customizations/numaplane.numaproj.io/MonoVertexRollout/actions/pause/action.lua)
- [numaplane.numaproj.io/MonoVertexRollout/unpause](https://github.com/argoproj/argo-cd/blob/master/resource_customizations/numaplane.numaproj.io/MonoVertexRollout/actions/unpause/action.lua)
- [numaplane.numaproj.io/PipelineRollout/allow-data-loss](https://github.com/argoproj/argo-cd/blob/master/resource_customizations/numaplane.numaproj.io/PipelineRollout/actions/allow-data-loss/action.lua)
-- [numaplane.numaproj.io/PipelineRollout/disable-force-promote](https://github.com/argoproj/argo-cd/blob/master/resource_customizations/numaplane.numaproj.io/PipelineRollout/actions/disable-force-promote/action.lua)
- [numaplane.numaproj.io/PipelineRollout/disallow-data-loss](https://github.com/argoproj/argo-cd/blob/master/resource_customizations/numaplane.numaproj.io/PipelineRollout/actions/disallow-data-loss/action.lua)
-- [numaplane.numaproj.io/PipelineRollout/enable-force-promote](https://github.com/argoproj/argo-cd/blob/master/resource_customizations/numaplane.numaproj.io/PipelineRollout/actions/enable-force-promote/action.lua)
- [numaplane.numaproj.io/PipelineRollout/pause](https://github.com/argoproj/argo-cd/blob/master/resource_customizations/numaplane.numaproj.io/PipelineRollout/actions/pause/action.lua)
- [numaplane.numaproj.io/PipelineRollout/unpause](https://github.com/argoproj/argo-cd/blob/master/resource_customizations/numaplane.numaproj.io/PipelineRollout/actions/unpause/action.lua)
- [source.toolkit.fluxcd.io/Bucket/reconcile](https://github.com/argoproj/argo-cd/blob/master/resource_customizations/source.toolkit.fluxcd.io/Bucket/actions/reconcile/action.lua)
diff --git a/docs/operator-manual/secret-management.md b/docs/operator-manual/secret-management.md
index e141e952c3..95343789c4 100644
--- a/docs/operator-manual/secret-management.md
+++ b/docs/operator-manual/secret-management.md
@@ -1,47 +1,29 @@
# Secret Management
-There are two general ways to populate secrets when doing GitOps: on the destination cluster, or in Argo CD during
-manifest generation. We strongly recommend the former, as it is more secure and provides a better user experience.
+Argo CD is un-opinionated about how secrets are managed. There are many ways to do it, and there's no one-size-fits-all solution.
-For further discussion, see [#1364](https://github.com/argoproj/argo-cd/issues/1364).
+Many solutions use plugins to inject secrets into the application manifests. See [Mitigating Risks of Secret-Injection Plugins](#mitigating-risks-of-secret-injection-plugins)
+below to make sure you use those plugins securely.
-## Destination Cluster Secret Management
+Here are some ways people are doing GitOps secrets:
-In this approach, secrets are populated on the destination cluster, and Argo CD does not need to directly manage them.
-[Sealed Secrets](https://github.com/bitnami-labs/sealed-secrets), [External Secrets Operator](https://github.com/external-secrets/external-secrets),
-and [Kubernetes Secrets Store CSI Driver](https://github.com/kubernetes-sigs/secrets-store-csi-driver) are examples of this style of secret management.
-
-This approach has two main advantages:
-
-1) Security: Argo CD does not need to have access to the secrets, which reduces the risk of leaking them.
-2) User Experience: Secret updates are decoupled from app sync operations, which reduces the risk of unintentionally
- applying Secret updates during an unrelated release.
-
-We strongly recommend this style of secret management.
-
-Other examples of this style of secret management include:
+* [Bitnami Sealed Secrets](https://github.com/bitnami-labs/sealed-secrets)
+* [External Secrets Operator](https://github.com/external-secrets/external-secrets)
+* [Hashicorp Vault](https://www.vaultproject.io)
+* [Bank-Vaults](https://bank-vaults.dev/)
+* [Helm Secrets](https://github.com/jkroepke/helm-secrets)
+* [Kustomize secret generator plugins](https://github.com/kubernetes-sigs/kustomize/blob/fd7a353df6cece4629b8e8ad56b71e30636f38fc/examples/kvSourceGoPlugin.md#secret-values-from-anywhere)
* [aws-secret-operator](https://github.com/mumoshu/aws-secret-operator)
-* [Vault Secrets Operator](https://developer.hashicorp.com/vault/docs/platform/k8s/vso)
+* [KSOPS](https://github.com/viaduct-ai/kustomize-sops#argo-cd-integration)
+* [argocd-vault-plugin](https://github.com/argoproj-labs/argocd-vault-plugin)
+* [argocd-vault-replacer](https://github.com/crumbhole/argocd-vault-replacer)
+* [Kubernetes Secrets Store CSI Driver](https://github.com/kubernetes-sigs/secrets-store-csi-driver)
+* [Vals-Operator](https://github.com/digitalis-io/vals-operator)
+* [argocd-secret-replacer](https://github.com/mmalyska/argocd-secret-replacer)
-## Argo CD Manifest Generation-Based Secret Management
+For discussion, see [#1364](https://github.com/argoproj/argo-cd/issues/1364)
-In this approach, Argo CD's manifest generation step is used to inject secrets. This may be done using a
-[Config Management Plugin](config-management-plugins.md) like [argocd-vault-plugin](https://github.com/argoproj-labs/argocd-vault-plugin).
-
-**We strongly caution against this style of secret management**, as it has several disadvantages:
-
-1) Security: Argo CD needs access to the secrets, which increases the risk of leaking them. Argo CD stores generated
- manifests in plaintext in its Redis cache, so injecting secrets into the manifests increases risk.
-2) User Experience: Secret updates are coupled with app sync operations, which increases the risk of unintentionally
- applying Secret updates during an unrelated release.
-3) Rendered Manifests Pattern: This approach is incompatible with the "Rendered Manifests" pattern, which is
- increasingly becoming a best practice for GitOps.
-
-Many users have already adopted generation-based solutions, and we understand that migrating to an operator-based
-solution can be a significant effort. Argo CD will continue to support generation-based secret management, but we will
-not prioritize new features or improvements that solely support this style of secret management.
-
-### Mitigating Risks of Secret-Injection Plugins
+## Mitigating Risks of Secret-Injection Plugins
Argo CD caches the manifests generated by plugins, along with the injected secrets, in its Redis instance. Those
manifests are also available via the repo-server API (a gRPC service). This means that the secrets are available to
@@ -52,3 +34,4 @@ Consider these steps to mitigate the risks of secret-injection plugins:
1. Set up network policies to prevent direct access to Argo CD components (Redis and the repo-server). Make sure your
cluster supports those network policies and can actually enforce them.
2. Consider running Argo CD on its own cluster, with no other applications running on it.
+
diff --git a/docs/operator-manual/security.md b/docs/operator-manual/security.md
index afee322551..9d05c45cb7 100644
--- a/docs/operator-manual/security.md
+++ b/docs/operator-manual/security.md
@@ -238,14 +238,6 @@ can be found in [server/server.go](https://github.com/argoproj/argo-cd/blob/abba
Argo CD does not log IP addresses of clients requesting API endpoints, since the API server is typically behind a proxy. Instead, it is recommended
to configure IP addresses logging in the proxy server that sits in front of the API server.
-### Standard Application log fields
-
-For logs related to an Application, Argo CD will log the following standard fields :
-
-* *application*: the Application name, without the namespace
-* *app-namespace*: the Application's namespace
-* *project*: the Application's project
-
## ApplicationSets
Argo CD's ApplicationSets feature has its own [security considerations](./applicationset/Security.md). Be aware of those
diff --git a/docs/operator-manual/server-commands/additional-configuration-method.md b/docs/operator-manual/server-commands/additional-configuration-method.md
index d570393310..cc80ed3aeb 100644
--- a/docs/operator-manual/server-commands/additional-configuration-method.md
+++ b/docs/operator-manual/server-commands/additional-configuration-method.md
@@ -23,6 +23,6 @@ To set `logformat` of `argocd-application-controller`, add below entry to the co
```
data:
- controller.log.format: "json"
+ controller.log.format: "text"
```
diff --git a/docs/operator-manual/server-commands/argocd-application-controller.md b/docs/operator-manual/server-commands/argocd-application-controller.md
index 29c6b95d7f..f4c6776bc7 100644
--- a/docs/operator-manual/server-commands/argocd-application-controller.md
+++ b/docs/operator-manual/server-commands/argocd-application-controller.md
@@ -16,8 +16,8 @@ argocd-application-controller [flags]
```
--app-hard-resync int Time period in seconds for application hard resync.
- --app-resync int Time period in seconds for application resync. (default 120)
- --app-resync-jitter int Maximum time period in seconds to add as a delay jitter for application resync. (default 60)
+ --app-resync int Time period in seconds for application resync. (default 180)
+ --app-resync-jitter int Maximum time period in seconds to add as a delay jitter for application resync.
--app-state-cache-expiration duration Cache expiration for app state (default 1h0m0s)
--application-namespaces strings List of additional namespaces that applications are allowed to be reconciled from
--as string Username to impersonate for the operation
@@ -40,12 +40,11 @@ argocd-application-controller [flags]
--insecure-skip-tls-verify If true, the server's certificate will not be checked for validity. This will make your HTTPS connections insecure
--kubeconfig string Path to a kube config. Only required if out-of-cluster
--kubectl-parallelism-limit int Number of allowed concurrent kubectl fork/execs. Any value less than 1 means no limit. (default 20)
- --logformat string Set the logging format. One of: json|text (default "json")
+ --logformat string Set the logging format. One of: text|json (default "text")
--loglevel string Set the logging level. One of: debug|info|warn|error (default "info")
--metrics-application-conditions strings List of Application conditions that will be added to the argocd_application_conditions metric
--metrics-application-labels strings List of Application labels that will be added to the argocd_application_labels metric
--metrics-cache-expiration duration Prometheus metrics cache expiration (disabled by default. e.g. 24h0m0s)
- --metrics-cluster-labels strings List of Cluster labels that will be added to the argocd_cluster_labels metric
--metrics-port int Start metrics server on given port (default 8082)
-n, --namespace string If present, the namespace scope for this CLI request
--operation-processors int Number of application operation processors (default 10)
@@ -54,7 +53,7 @@ argocd-application-controller [flags]
--otlp-headers stringToString List of OpenTelemetry collector extra headers sent with traces, headers are comma-separated key-value pairs(e.g. key1=value1,key2=value2) (default [])
--otlp-insecure OpenTelemetry collector insecure mode (default true)
--password string Password for basic authentication to the API server
- --persist-resource-health Enables storing the managed resources health in the Application CRD
+ --persist-resource-health Enables storing the managed resources health in the Application CRD (default true)
--proxy-url string If provided, this URL will be used to connect via proxy
--redis string Redis server hostname and port (e.g. argocd-redis:6379).
--redis-ca-certificate string Path to Redis server CA certificate (e.g. /etc/certs/redis/ca.crt). If not specified, system trusted CAs will be used for server certificate validation.
diff --git a/docs/operator-manual/server-commands/argocd-applicationset-controller.md b/docs/operator-manual/server-commands/argocd-applicationset-controller.md
deleted file mode 100644
index 4fbe98d324..0000000000
--- a/docs/operator-manual/server-commands/argocd-applicationset-controller.md
+++ /dev/null
@@ -1,62 +0,0 @@
-# `argocd-applicationset-controller` Command Reference
-
-## argocd-applicationset-controller
-
-Starts Argo CD ApplicationSet controller
-
-```
-argocd-applicationset-controller [flags]
-```
-
-### Options
-
-```
- --allowed-scm-providers strings The list of allowed custom SCM provider API URLs. This restriction does not apply to SCM or PR generators which do not accept a custom API URL. (Default: Empty = all)
- --applicationset-namespaces strings Argo CD applicationset namespaces
- --argocd-repo-server string Argo CD repo server address (default "argocd-repo-server:8081")
- --as string Username to impersonate for the operation
- --as-group stringArray Group to impersonate for the operation, this flag can be repeated to specify multiple groups.
- --as-uid string UID to impersonate for the operation
- --certificate-authority string Path to a cert file for the certificate authority
- --client-certificate string Path to a client certificate file for TLS
- --client-key string Path to a client key file for TLS
- --cluster string The name of the kubeconfig cluster to use
- --concurrent-reconciliations int Max concurrent reconciliations limit for the controller (default 10)
- --context string The name of the kubeconfig context to use
- --debug Print debug logs. Takes precedence over loglevel
- --disable-compression If true, opt-out of response compression for all requests to the server
- --dry-run Enable dry run mode
- --enable-leader-election Enable leader election for controller manager. Enabling this will ensure there is only one active controller manager.
- --enable-new-git-file-globbing Enable new globbing in Git files generator.
- --enable-policy-override For security reason if 'policy' is set, it is not possible to override it at applicationSet level. 'allow-policy-override' allows user to define their own policy (default true)
- --enable-progressive-syncs Enable use of the experimental progressive syncs feature.
- --enable-scm-providers Enable retrieving information from SCM providers, used by the SCM and PR generators (Default: true) (default true)
- -h, --help help for argocd-applicationset-controller
- --insecure-skip-tls-verify If true, the server's certificate will not be checked for validity. This will make your HTTPS connections insecure
- --kubeconfig string Path to a kube config. Only required if out-of-cluster
- --logformat string Set the logging format. One of: json|text (default "json")
- --loglevel string Set the logging level. One of: debug|info|warn|error (default "info")
- --metrics-addr string The address the metric endpoint binds to. (default ":8080")
- --metrics-applicationset-labels strings List of Application labels that will be added to the argocd_applicationset_labels metric
- -n, --namespace string If present, the namespace scope for this CLI request
- --password string Password for basic authentication to the API server
- --policy string Modify how application is synced between the generator and the cluster. Default is '' (empty), which means AppSets default to 'sync', but they may override that default. Setting an explicit value prevents AppSet-level overrides, unless --allow-policy-override is enabled. Explicit options are: 'sync' (create & update & delete), 'create-only', 'create-update' (no deletion), 'create-delete' (no update)
- --preserved-annotations strings Sets global preserved field values for annotations
- --preserved-labels strings Sets global preserved field values for labels
- --probe-addr string The address the probe endpoint binds to. (default ":8081")
- --proxy-url string If provided, this URL will be used to connect via proxy
- --repo-server-plaintext Disable TLS on connections to repo server
- --repo-server-strict-tls Whether to use strict validation of the TLS cert presented by the repo server
- --repo-server-timeout-seconds int Repo server RPC call timeout seconds. (default 60)
- --request-timeout string The length of time to wait before giving up on a single server request. Non-zero values should contain a corresponding time unit (e.g. 1s, 2m, 3h). A value of zero means don't timeout requests. (default "0")
- --scm-root-ca-path string Provide Root CA Path for self-signed TLS Certificates
- --server string The address and port of the Kubernetes API server
- --tls-server-name string If provided, this name will be used to validate server certificate. If this is not provided, hostname used to contact the server is used.
- --token string Bearer token for authentication to the API server
- --token-ref-strict-mode Set to true to require secrets referenced by SCM providers to have the argocd.argoproj.io/secret-type=scm-creds label set (Default: false)
- --user string The name of the kubeconfig user to use
- --username string Username for basic authentication to the API server
- --webhook-addr string The address the webhook endpoint binds to. (default ":7000")
- --webhook-parallelism-limit int Number of webhook requests processed concurrently (default 50)
-```
-
diff --git a/docs/operator-manual/server-commands/argocd-dex_gendexcfg.md b/docs/operator-manual/server-commands/argocd-dex_gendexcfg.md
index 6de925f1f1..a889b64133 100644
--- a/docs/operator-manual/server-commands/argocd-dex_gendexcfg.md
+++ b/docs/operator-manual/server-commands/argocd-dex_gendexcfg.md
@@ -24,7 +24,7 @@ argocd-dex gendexcfg [flags]
-h, --help help for gendexcfg
--insecure-skip-tls-verify If true, the server's certificate will not be checked for validity. This will make your HTTPS connections insecure
--kubeconfig string Path to a kube config. Only required if out-of-cluster
- --logformat string Set the logging format. One of: json|text (default "json")
+ --logformat string Set the logging format. One of: text|json (default "text")
--loglevel string Set the logging level. One of: debug|info|warn|error (default "info")
-n, --namespace string If present, the namespace scope for this CLI request
-o, --out string Output to the specified file instead of stdout
diff --git a/docs/operator-manual/server-commands/argocd-dex_rundex.md b/docs/operator-manual/server-commands/argocd-dex_rundex.md
index dc1d44ddd9..b2d453feba 100644
--- a/docs/operator-manual/server-commands/argocd-dex_rundex.md
+++ b/docs/operator-manual/server-commands/argocd-dex_rundex.md
@@ -24,7 +24,7 @@ argocd-dex rundex [flags]
-h, --help help for rundex
--insecure-skip-tls-verify If true, the server's certificate will not be checked for validity. This will make your HTTPS connections insecure
--kubeconfig string Path to a kube config. Only required if out-of-cluster
- --logformat string Set the logging format. One of: json|text (default "json")
+ --logformat string Set the logging format. One of: text|json (default "text")
--loglevel string Set the logging level. One of: debug|info|warn|error (default "info")
-n, --namespace string If present, the namespace scope for this CLI request
--password string Password for basic authentication to the API server
diff --git a/docs/operator-manual/server-commands/argocd-repo-server.md b/docs/operator-manual/server-commands/argocd-repo-server.md
index bd3d5602b7..12e4d34d14 100644
--- a/docs/operator-manual/server-commands/argocd-repo-server.md
+++ b/docs/operator-manual/server-commands/argocd-repo-server.md
@@ -24,7 +24,7 @@ argocd-repo-server [flags]
--helm-registry-max-index-size string Maximum size of registry index file (default "1G")
-h, --help help for argocd-repo-server
--include-hidden-directories Include hidden directories from Git
- --logformat string Set the logging format. One of: json|text (default "json")
+ --logformat string Set the logging format. One of: text|json (default "text")
--loglevel string Set the logging level. One of: debug|info|warn|error (default "info")
--max-combined-directory-manifests-size string Max combined size of manifest files in a directory-type Application (default "10M")
--metrics-address string Listen on given address for metrics (default "0.0.0.0")
diff --git a/docs/operator-manual/server-commands/argocd-server.md b/docs/operator-manual/server-commands/argocd-server.md
index ba4e9fccfe..fe284a5940 100644
--- a/docs/operator-manual/server-commands/argocd-server.md
+++ b/docs/operator-manual/server-commands/argocd-server.md
@@ -59,7 +59,7 @@ argocd-server [flags]
--insecure Run server without TLS
--insecure-skip-tls-verify If true, the server's certificate will not be checked for validity. This will make your HTTPS connections insecure
--kubeconfig string Path to a kube config. Only required if out-of-cluster
- --logformat string Set the logging format. One of: json|text (default "json")
+ --logformat string Set the logging format. One of: text|json (default "text")
--login-attempts-expiration duration Cache expiration for failed login attempts (default 24h0m0s)
--loglevel string Set the logging level. One of: debug|info|warn|error (default "info")
--metrics-address string Listen for metrics on given address (default "0.0.0.0")
@@ -105,7 +105,6 @@ argocd-server [flags]
--sentinelmaster string Redis sentinel master group name. (default "master")
--server string The address and port of the Kubernetes API server
--staticassets string Directory path that contains additional static assets (default "/shared/app")
- --sync-with-replace-allowed Whether to allow users to select replace for syncs from UI/CLI (default true)
--tls-server-name string If provided, this name will be used to validate server certificate. If this is not provided, hostname used to contact the server is used.
--tlsciphers string The list of acceptable ciphers to be used when establishing TLS connections. Use 'list' to list available ciphers. (default "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384")
--tlsmaxversion string The maximum SSL/TLS version that is acceptable (one of: 1.0|1.1|1.2|1.3) (default "1.3")
diff --git a/docs/operator-manual/tested-kubernetes-versions.md b/docs/operator-manual/tested-kubernetes-versions.md
index 73475e8523..174ce6e051 100644
--- a/docs/operator-manual/tested-kubernetes-versions.md
+++ b/docs/operator-manual/tested-kubernetes-versions.md
@@ -1,2 +1,5 @@
-This page is populated for released Argo CD versions. Use the version selector to view this table for a specific
-version.
+| Argo CD version | Kubernetes versions |
+|-----------------|---------------------|
+| 2.14 | v1.31, v1.30, v1.29, v1.28 |
+| 2.13 | v1.30, v1.29, v1.28, v1.27 |
+| 2.12 | v1.29, v1.28, v1.27, v1.26 |
diff --git a/docs/operator-manual/tls.md b/docs/operator-manual/tls.md
index 4a094c59fc..43409fc568 100644
--- a/docs/operator-manual/tls.md
+++ b/docs/operator-manual/tls.md
@@ -2,7 +2,7 @@
Argo CD provides three inbound TLS endpoints that can be configured:
-* The user-facing endpoint of the `argocd-server` workload, which serves the UI
+* The user-facing endpoint of the `argocd-server` workload which serves the UI
and the API
* The endpoint of the `argocd-repo-server`, which is accessed by `argocd-server`
and `argocd-application-controller` workloads to request repository
@@ -11,7 +11,7 @@ Argo CD provides three inbound TLS endpoints that can be configured:
to handle OIDC authentication.
By default, and without further configuration, these endpoints will be
-set up to use an automatically generated, self-signed certificate. However,
+set-up to use an automatically generated, self-signed certificate. However,
most users will want to explicitly configure the certificates for these TLS
endpoints, possibly using automated means such as `cert-manager` or using
their own dedicated Certificate Authority.
@@ -39,7 +39,7 @@ There are two ways to configure the TLS certificates used by `argocd-server`:
`argocd-server-tls` secret may be of type `tls`, but does not have to be.
* Setting the `tls.crt` and `tls.key` keys in the `argocd-secret` secret to
hold PEM data of the certificate and the corresponding private key. This
- method is considered deprecated and only exists for purposes of backwards
+ method is considered deprecated, and only exists for purposes of backwards
compatibility. Changing `argocd-secret` should not be used to override the
TLS certificate anymore.
@@ -50,7 +50,7 @@ Argo CD decides which TLS certificate to use for the endpoint of
`tls.crt` and `tls.key` keys, this will be used for the certificate of the
endpoint of `argocd-server`.
* Otherwise, if the `argocd-secret` secret contains a valid key pair in the
- `tls.crt` and `tls.key` keys, this will be used as the certificate for the
+ `tls.crt` and `tls.key` keys, this will be used as certificate for the
endpoint of `argocd-server`.
* If no `tls.crt` and `tls.key` keys are found in neither of the two mentioned
secrets, Argo CD will generate a self-signed certificate and persist it in
@@ -69,7 +69,7 @@ kubectl create -n argocd secret tls argocd-server-tls \
```
Argo CD will pick up changes to the `argocd-server-tls` secret automatically
-and will not require restarting to use a renewed certificate.
+and will not require restart of the pods to use a renewed certificate.
## Configuring inbound TLS for argocd-repo-server
@@ -83,7 +83,7 @@ setting command line parameters. The following parameters are available:
|`--disable-tls`|`false`|Disables TLS completely|
|`--tlsminversion`|`1.2`|The minimum TLS version to be offered to clients|
|`--tlsmaxversion`|`1.3`|The maximum TLS version to be offered to clients|
-|`--tlsciphers`|`TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:TLS_RSA_WITH_AES_256_GCM_SHA384`|A colon-separated list of TLS cipher suites to be offered to clients|
+|`--tlsciphers`|`TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:TLS_RSA_WITH_AES_256_GCM_SHA384`|A colon separated list of TLS cipher suites to be offered to clients|
### Inbound TLS certificates used by argocd-repo-server
@@ -158,10 +158,10 @@ on how your workloads connect to the repository server.
Both `argocd-server` and `argocd-application-controller` communicate with the
`argocd-repo-server` using a gRPC API over TLS. By default,
-`argocd-repo-server` generates a non-persistent, self-signed certificate
+`argocd-repo-server` generates a non-persistent, self signed certificate
to use for its gRPC endpoint on startup. Because the `argocd-repo-server` has
-no means to connect to the K8s control plane API, this certificate is not available
-to outside consumers for verification. Both,
+no means to connect to the K8s control plane API, this certificate is not
+being available to outside consumers for verification. Both, the
`argocd-server` and `argocd-application-server` will use a non-validating
connection to the `argocd-repo-server` for this reason.
@@ -181,18 +181,19 @@ validate the TLS certificate of the `argocd-repo-server` by using the
certificate stored in the `argocd-repo-server-tls` secret.
!!!note "Certificate expiry"
- Please make sure that the certificate has a proper lifetime. Remember,
- when replacing certificates, all workloads must be restarted to pick up
- the certificate and work properly.
+ Please make sure that the certificate has a proper life time. Keep in
+ mind that when you have to replace the certificate, all workloads have
+ to be restarted in order to properly work again.
### Configuring TLS to argocd-dex-server
`argocd-server` communicates with the `argocd-dex-server` using an HTTPS API
-over TLS. By default, `argocd-dex-server` generates a non-persistent, self-signed
-certificate for its HTTPS endpoint on startup. Because `argocd-dex-server`
-has no means to connect to the K8s control plane API, this certificate is not
-available to outside consumers for verification. `argocd-server` will use a
-non-validating connection to `argocd-dex-server` for this reason.
+over TLS. By default, `argocd-dex-server` generates a non-persistent, self
+signed certificate to use for its HTTPS endpoint on startup. Because the
+`argocd-dex-server` has no means to connect to the K8s control plane API,
+this certificate is not being available to outside consumers for verification.
+The `argocd-server` will use a non-validating connection to the `argocd-dex-server`
+for this reason.
To change this behavior to be more secure by having the `argocd-server` validate
the TLS certificate of the `argocd-dex-server` endpoint, the following steps need
@@ -209,14 +210,14 @@ The `argocd-server` workload will now validate the TLS certificate of the
secret.
!!!note "Certificate expiry"
- Please make sure that the certificate has a proper lifetime. Remember,
- when replacing certificates, all workloads must be restarted to pick up
- the certificate and work properly.
+ Please make sure that the certificate has a proper life time. Keep in
+ mind that when you have to replace the certificate, all workloads have
+ to be restarted in order to properly work again.
### Disabling TLS to argocd-repo-server
-In some scenarios where mTLS through sidecar proxies is involved (e.g.
-in a service mesh), you may want to configure the connections between the
+In some scenarios where mTLS through side-car proxies is involved (e.g.
+in a service mesh), you may want configure the connections between the
`argocd-server` and `argocd-application-controller` to `argocd-repo-server`
to not use TLS at all.
@@ -225,36 +226,36 @@ In this case, you will need to:
* Configure `argocd-repo-server` with TLS on the gRPC API disabled by specifying
the `--disable-tls` parameter to the pod container's startup arguments.
Also, consider restricting listening addresses to the loopback interface by specifying
- `--listen 127.0.0.1` parameter, so that the insecure endpoint is not exposed on
- the pod's network interfaces, but still available to the sidecar container.
+ `--listen 127.0.0.1` parameter, so that insecure endpoint is not exposed on
+ the pod's network interfaces, but still available to the side-car container.
* Configure `argocd-server` and `argocd-application-controller` to not use TLS
for connections to the `argocd-repo-server` by specifying the parameter
`--repo-server-plaintext` to the pod container's startup arguments
* Configure `argocd-server` and `argocd-application-controller` to connect to
- the sidecar instead of directly to the `argocd-repo-server` service by
+ the side-car instead of directly to the `argocd-repo-server` service by
specifying its address via the `--repo-server ` parameter
-After this change, `argocd-server` and `argocd-application-controller` will
-use a plain text connection to the sidecar proxy, which will handle all aspects
-of TLS to `argocd-repo-server`'s TLS sidecar proxy.
+After this change, the `argocd-server` and `argocd-application-controller` will
+use a plain text connection to the side-car proxy, that will handle all aspects
+of TLS to the `argocd-repo-server`'s TLS side-car proxy.
### Disabling TLS to argocd-dex-server
-In some scenarios where mTLS through sidecar proxies is involved (e.g.
-in a service mesh), you may want to configure the connections between
+In some scenarios where mTLS through side-car proxies is involved (e.g.
+in a service mesh), you may want configure the connections between
`argocd-server` to `argocd-dex-server` to not use TLS at all.
In this case, you will need to:
* Configure `argocd-dex-server` with TLS on the HTTPS API disabled by specifying
the `--disable-tls` parameter to the pod container's startup arguments
-* Configure `argocd-server` to not use TLS for connections to `argocd-dex-server`
+* Configure `argocd-server` to not use TLS for connections to the `argocd-dex-server`
by specifying the parameter `--dex-server-plaintext` to the pod container's startup
arguments
-* Configure `argocd-server` to connect to the sidecar instead of directly to the
+* Configure `argocd-server` to connect to the side-car instead of directly to the
`argocd-dex-server` service by specifying its address via the `--dex-server `
parameter
-After this change, `argocd-server` will use a plain text connection to the sidecar
-proxy, that will handle all aspects of TLS to the `argocd-dex-server`'s TLS sidecar proxy.
+After this change, the `argocd-server` will use a plain text connection to the side-car
+proxy, that will handle all aspects of TLS to the `argocd-dex-server`'s TLS side-car proxy.
diff --git a/docs/operator-manual/upgrading/2.13-2.14.md b/docs/operator-manual/upgrading/2.13-2.14.md
index 3b8a473fb4..4ee50fd1c1 100644
--- a/docs/operator-manual/upgrading/2.13-2.14.md
+++ b/docs/operator-manual/upgrading/2.13-2.14.md
@@ -1,13 +1,5 @@
# v2.13 to 2.14
-## Avoid v2.14.0 manifests and use v2.14.1
-
-The tagged v2.14.0 manifests contain a nonexistent Argo CD image. If you are using the Argo CD manifests as a remote
-base, use the v2.14.1 manifests instead.
-
-Eg, `https://github.com/argoproj/argo-cd/manifests/ha/cluster-install?ref=v2.14.1` or
-`https://raw.githubusercontent.com/argoproj/argo-cd/v2.14.1/manifests/install.yaml`
-
## Upgraded Helm Version
Helm was upgraded to 3.16.2 and the skipSchemaValidation Flag was added to
diff --git a/docs/operator-manual/upgrading/2.14-3.0.md b/docs/operator-manual/upgrading/2.14-3.0.md
deleted file mode 100644
index fb9c16e1f2..0000000000
--- a/docs/operator-manual/upgrading/2.14-3.0.md
+++ /dev/null
@@ -1,466 +0,0 @@
-# v2.14 to 3.0
-
-Argo CD 3.0 is meant to be a low-risk upgrade containing only minor breaking changes. For each change, the next
-section will describe how to quickly determine if you are impacted, how to remediate the breaking change, and (if
-applicable) restore Argo CD 2.x default behavior.
-
-Once 3.0 is released, no more 2.x minor versions will be released. We will continue to cut patch releases for the two
-most recent minor versions (so 2.14 until 3.2 is released and 2.13 until 3.1 is released).
-
-## Breaking Changes
-
-### Fine-Grained RBAC for application `update` and `delete` sub-resources
-
-The default behavior of fine-grained policies have changed so they no longer apply to sub-resources.
-Prior to v3, policies granting `update` or `delete` to an application also applied to any of its sub-resources.
-
-Starting with v3, the `update` or `delete` actions only apply to the application itself. New policies must be defined
-to allow the `update/*` or `delete/*` actions on an Application's managed resources.
-
-The v2 behavior can be preserved by setting the config value `server.rbac.disableApplicationFineGrainedRBACInheritance`
-to `false` in the Argo CD ConfigMap `argocd-cm`.
-
-Read the [RBAC documentation](../rbac.md#fine-grained-permissions-for-updatedelete-action) for more detailed
-information.
-
-### Logs RBAC enforcement as a first-class RBAC citizen
-
-2.4 introduced `logs` as a new RBAC resource. In 2.3 and lower, users with `applications, get` access automatically got logs access. In 2.4, it became possible to enable logs RBAC enforcement with a flag in `argocd-cm` ConfigMap:
-
-```yaml
-server.rbac.log.enforce.enable: 'true'
-```
-
-Starting from 3.0, this flag is removed and the logs RBAC is enforced by default, meaning the `logs` tab on `pod` view will not be visible without granting explicit `logs, get` permissions to the users/groups/roles requiring it.
-
-#### Detection
-
-Users who have `server.rbac.log.enforce.enable: "true"` in their `argocd-cm` ConfigMap, are unaffected by this change.
-
-Users who have `policy.default: role:readonly` or `policy.default: role:admin` in their `argocd-rbac-cm` ConfigMap, are unaffected.
-
-Users who don't have a `policy.default` in their `argocd-rbac-cm` ConfigMap, and either have `server.rbac.log.enforce.enable` set to `false` or don't have this setting at all in their `argocd-cm` ConfigMap are affected and should perform the below remediation steps.
-
-After the upgrade, it is recommended to remove the setting `server.rbac.log.enforce.enable` from `argocd-cm` ConfigMap, if it was there before the upgrade.
-
-#### Remediation
-
-##### Quick remediation (global change)
-
-For users with an existing default policy with a custom role, add this policy to `policy.csv` for your custom role: `p, role:, logs, get, */*, allow`.
-For users without a default policy, add this policy to `policy.csv`: `p, role:global-log-viewer, logs, get, */*, allow` and add the default policy for this role: `policy.default: role:global-log-viewer`
-
-##### Recommended remediation (per-policy change)
-
-Explicitly add a `logs, get` policy to every role that has a policy for `applications, get` or for `applications, *`.
-This is the recommended way to maintain the principle of least privilege.
-Similar to the way access to Applications are currently managed, access to logs can be either granted on a Project scope level (Project resource) or on the `argocd-rbac-cm` ConfigMap level.
-See this [example](../upgrading/2.3-2.4.md#example-1) for more details.
-
-### Default `resource.exclusions` configurations
-
-Argo CD manifest now contains a default configuration for `resource.exclusions` in the `argocd-cm` to exclude resources that
-are known to be created by controllers and not usually managed in Git. The exclusions contain high volume and high churn objects
-which we exclude for performance reasons, reducing connections and load to the K8s API servers of managed clusters.
-
-The excluded Kinds are:
-
-- **Kubernetes Resources**: `Endpoints`, `EndpointSlice`, `Lease`, `SelfSubjectReview`, `TokenReview`, `LocalSubjectAccessReview`, `SelfSubjectAccessReview`, `SelfSubjectRulesReview`, `SubjectAccessReview`, `CertificateSigningRequest`, `PolicyReport` and `ClusterPolicyReport`.
-- **Cert Manager**: `CertificateRequest`.
-- **Kyverno**: `EphemeralReport`, `ClusterEphemeralReport`, `AdmissionReport`, `ClusterAdmissionReport`, `BackgroundScanReport`, `ClusterBackgroundScanReport` and `UpdateRequest`.
-- **Cilium**: `CiliumIdentity`, `CiliumEndpoint` and `CiliumEndpointSlice`.
-
-The default `resource.exclusions` can be overridden or removed in the configMap to preserve the v2 behavior.
-
-Read the [Declarative Setup](../declarative-setup.md) for more detailed information to configure `resource.exclusions`.
-
-### Removal of `argocd_app_sync_status`, `argocd_app_health_status` and `argocd_app_created_time` Metrics
-
-The `argocd_app_sync_status`, `argocd_app_health_status` and `argocd_app_created_time`, deprecated and disabled by
-default since 1.5.0, have been removed. The information previously provided by these metrics is now available as labels
-on the `argocd_app_info` metric.
-
-#### Detection
-
-Starting with 1.5.0, these metrics are only available if `ARGOCD_LEGACY_CONTROLLER_METRICS` is explicitly set to `true`.
-If it is not set to true, you can safely upgrade with no changes.
-
-#### Migration
-
-If you are using these metrics, you will need to update your monitoring dashboards and alerts to use the new metric and
-labels before upgrading.
-
-### Changes to RBAC with Dex SSO Authentication
-
-When using Dex, the `sub` claim returned in the authentication was used as the subject for RBAC. That value depends on
-the Dex internal implementation and should not be considered an immutable value that represents the subject.
-
-The new behavior will request the
-`federated:id` [scope](https://dexidp.io/docs/configuration/custom-scopes-claims-clients/) from Dex, and the new value
-used as the RBAC subject will be based
-on the `federated_claims.user_id` claim instead of the `sub` claim.
-
-If you were using the Dex sub claim in RBAC policies, you will need to update them to maintain the same access.
-
-You can know the correct `user_id` to use by decoding the current `sub` claims defined in your policies. You can also
-configure which
-value is used as `user_id` for some [connectors](https://dexidp.io/docs/connectors/).
-
-```sh
-$> echo "ChdleGFtcGxlQGFyZ29wcm9qLmlvEgJkZXhfY29ubl9pZA" | base64 -d
-
-example@argoproj.iodex_conn_i%
-```
-
-```yaml
-# Policies based on the Dex sub claim (wrong)
-- g, ChdleGFtcGxlQGFyZ29wcm9qLmlvEgJkZXhfY29ubl9pZA, role:example
-- p, ChdleGFtcGxlQGFyZ29wcm9qLmlvEgJkZXhfY29ubl9pZA, applications, *, *, allow
-
-# Policies now based on federated_claims.user_id claim (correct)
-- g, example@argoproj.io, role:example
-- p, example@argoproj.io, applications, *, *, allow
-```
-
-If authenticating with the CLI, make sure to use the new version as well to obtain an authentication token with the
-appropriate claims.
-
-### Removed support for legacy repo config in argocd-cm
-
-Before repositories were managed as Secrets, they were configured in the argocd-cm ConfigMap. The argocd-cm option has
-been deprecated for some time and is no longer available in Argo CD 3.0.
-
-#### Detection
-
-To check whether you have any repositories configured in argocd-cm, run the following command:
-
-```shell
-kubectl get cm argocd-cm -o=jsonpath="[{.data.repositories}, {.data['repository\.credentials']}, {.data['helm\.repositories']}]"
-```
-
-If you have no repositories configured in argocd-cm, the output will be `[, , ]`, and you are not impacted by this
-change.
-
-#### Migration
-
-To convert your repositories to Secrets, follow the documentation for
-[declarative management of repositories](../declarative-setup.md#repositories).
-
-### Ignoring ApplicationSet `applyNestedSelectors` field
-
-Setting the `spec.applyNestedSelectors` field in an ApplicationSet resolves counter-intuitive behavior where filters in
-nested selectors were not applied. Starting in Argo CD 3.0, the field is ignored, and behavior is always the same as if
-`applyNestedSelectors` was set to `true`. In other words, nested selectors are always applied.
-
-#### Detection
-
-To detect if you are impacted, search your ApplicationSet controller logs for this string: `ignoring nested selector`.
-If there are no logs with this string, you are not impacted.
-
-Another way to detect if you are impacted is to run the following command:
-
-```shell
-kubectl get appsets -o=json | jq -r '.items[] | select(
- .spec.applyNestedSelectors != true and
- .spec.generators[][].generators[][].generators[].selector != null
- ) | .metadata.name'
-```
-
-The command will print the name of any ApplicationSet that has `applyNestedSelectors` unset or set to `false` and has
-one or more nested selectors.
-
-#### Remediation
-
-Since `applyNestedSelectors` is false by default, you can safely remove the nested selectors on ApplicationSets where
-`applyNestedSelectors` has not been explicitly set to `true`. After the selectors are removed, you can safely upgrade.
-
-For example, you should remove the selector in this ApplicationSet before upgrading to Argo CD 3.0.
-
-```diff
-apiVersion: argoproj.io/v1alpha1
-kind: ApplicationSet
-metadata:
- name: guestbook
-spec:
- goTemplate: true
- goTemplateOptions: ["missingkey=error"]
- generators:
- - matrix:
- mergeKeys: ['test-key']
- generators:
- - list:
- elements:
- - test-key: 'test-value'
- cluster: staging
- - test-key: 'test-value'
- cluster: production
- - merge:
- generators:
- - list:
- elements:
- - another-key: 'another-value'
- - cluster: {}
-- selector:
-- matchLabels:
-- app: guestbook
-
- template:
- metadata:
- name: '{{.cluster}}-guestbook'
- spec:
- project: my-project
- source:
- repoURL: https://github.com/infra-team/cluster-deployments.git
- targetRevision: HEAD
- path: guestbook/{{.cluster}}
- destination:
- server: '{{.url}}'
- namespace: guestbook
-```
-
-### Upgraded Helm version with breaking changes
-
-Helm was upgraded to 3.17.1.
-This may require changing your `values.yaml` files for subcharts, if the `values.yaml` contain a section with a `null` object.
-See related issue in [Helm GitHub repository](https://github.com/helm/helm/issues/12469)
-See Helm 3.17.1 [release notes](https://github.com/helm/helm/releases/tag/v3.17.1)
-Example of such a [problem and resolution](https://github.com/argoproj/argo-cd/pull/22035/files)
-Explanation:
-
-- Prior to Helm 3.17.1, `null` object in `values.yaml` resulted in a warning: `cannot overwrite table with non table` upon performing `helm template`, and the resulting K8s object was not overridden with the invalid `null` value.
-- In Helm 3.17.1, this behavior changed and `null` object in `values.yaml` still results in this warning upon performing `helm template`, but the resulting K8s object will be overridden with the invalid `null` value.
-- To resolve the issue, identify `values.yaml` with `null` object values, and remove those `null` values.
-
-### Use Annotation-Based Tracking by Default
-
-The default behavior for [tracking resources](../../user-guide/resource_tracking.md) has changed to use annotation-based
-tracking instead of label-based tracking. Annotation-based tracking is more reliable and less prone to errors caused by
-external code copying tracking labels from one resource to another.
-
-#### Detection
-
-To detect if you are impacted, check the `argocd-cm` ConfigMap for the `application.resourceTrackingMethod` field. If it
-unset or is set to `label`, you are using label-based tracking. If it is set to `annotation`, you are already using
-annotation-based tracking and are not impacted by this change.
-
-```sh
-kubectl get cm argocd-cm -n argocd -o jsonpath='{.data.application\.resourceTrackingMethod}'
-```
-
-#### Remediation
-
-For most users, it is safe to upgrade to Argo CD 3.0 and use annotation-based tracking. Labels will be replaced with
-annotations on the next sync. Applications will not be marked as out-of-sync if labels are not present on the
-resources.
-
-!!! warning "Potential for orphaned resources"
-
- There is a known edge case when switching from label-based tracking to annotation-based tracking that may cause
- resources to be orphaned. If the first sync operation after switching to annotation-based tracking includes a
- resource being deleted, Argo CD will fail to recognize that the resource is managed by the Application and will not
- delete it. To avoid this edge case, it is recommended to perform a sync operation on your Applications, even if
- they are not out of sync, so that orphan resource detection will work as expected on the next sync.
-
-Some users rely on label-based tracking to track resources that are not managed by Argo CD. They may set annotations
-to have Argo CD ignore the resource as extraneous or to disable pruning. If you are using label-based tracking to track
-resources that are not managed by Argo CD, you will need to construct tracking annotations instead of tracking labels
-and apply them to the relevant resources. The format of the tracking annotation is:
-
-```yaml
-argocd.argoproj.io/tracking-id: :/:/
-```
-
-For cluster-scoped resources, the namespace is set to the value in the Application's `spec.destination.namespace` field.
-
-!!! warning
-
- Manually constructing and applying tracking labels and annotations is not an officially supported feature, and Argo
- CD's behavior may change in the future. It is recommended to manage resources with Argo CD via GitOps.
-
-#### Opting Out
-
-If you are not ready to use annotation-based tracking, you can opt out of this change by setting the
-`application.resourceTrackingMethod` field in the `argocd-cm` ConfigMap to `label`. There are no current plans to remove
-label-based tracking.
-
-## Other changes
-
-### Using `cluster.inClusterEnabled: "false"`
-
-When `cluster.inClusterEnabled: "false"` is explicitly configured, Applications currently configured to
-sync on the in-cluster cluster will now be in an Unknown state, without the possibility to sync resources.
-
-It will not be possible to create new Applications using the in-cluster cluster. When deleting existing
-Application, it will not delete the previously managed resources.
-
-It is recommended to perform any cleanup or migration to existing in-cluster Application before upgrading
-when in-cluster is disabled. To perform cleanup post-migration, the in-cluster will need to be enabled temporarily.
-
-### Ignoring all status updates and high churn mutations
-
-Argo CD manifest now contains a default configuration for `resource.customizations.ignoreResourceUpdates` in the `argocd-cm`
-to exclude common resources that are often mutated in Kubernetes. These mutations are known to cause an unnecessary
-load on Argo CD. When a watched resource is modified, Argo CD will always ignore the `.status` changes.
-
-The default `resource.customizations.ignoreResourceUpdates` configurations can be overridden or removed in the configMap to preserve the v2 behavior.
-
-### Health status in the Application CR
-
-The health status of each object used to be persisted under `/status` in the Application CR by default.
-Any health churn in the resources deployed by the Application put load on the application controller.
-Now, the health status is stored externally.
-
-You can revert this behavior by setting the `controller.resource.health.persist` to `true` in the Argo CD
-`argocd-cmd-params-cm.yaml` Config Map.
-
-Example of a status field in the Application CR persisting health:
-
-```yaml
-status:
- health:
- status: Healthy
- lastTransitionTime: '2025-01-01T00:00:00Z'
- resources:
- - group: apps
- health:
- status: Healthy
- kind: Deployment
- name: my-app
- namespace: foo
- status: OutOfSync
- version: v1
- sync:
- status: OutOfSync
-```
-
-Example of a status field in the Application CR _not_ persisting health:
-
-```yaml
-status:
- health:
- status: Healthy
- lastTransitionTime: '2025-01-01T00:00:00Z'
- resourceHealthSource: appTree
- resources:
- - group: apps
- kind: Deployment
- name: my-app
- namespace: foo
- status: OutOfSync
- version: v1
- sync:
- status: OutOfSync
-```
-
-#### Detection
-
-1. Check the `argocd-cmd-params-cm.yaml` ConfigMap for `controller.resource.health.persist`.
-
- If the value is empty or true, the health status is persisted in the Application CR.
-
-```sh
-kubectl get cm argocd-cmd-params-cm -n argocd -o jsonpath='{.data.controller\.resource\.health\.persist}'
-```
-
-2. Check any Application CR for the `resourceHealthSource` field.
- If you see a blank value, the health status is persisted in the Application CR.
-
-```sh
-kubectl get applications.argoproj.io -n argocd -o jsonpath='{.status.resourceHealthSource}'
-```
-
-#### Migration
-
-Any tools or CLI commands parsing the `.status.resources[].health` need to be updated to use the argocd cli/API to get the health status.
-
-!!! note
- The application list API (argocd app list) no longer returns the individual health status of resources.
-
-```sh
-argocd app get -o json
-```
-
-### Empty Environment Variables in Plugins
-
-In Argo CD 3.0, empty environment variables are now passed to config management plugins.
-
-```yaml
-apiVersion: argoproj.io/v1alpha1
-kind: Application
-spec:
- source:
- plugin:
- name: example-plugin
- env:
- - name: VERSION
- value: '1.2.3'
- - name: DATA # Even though this is empty, it will be passed to the plugin as ARGOCD_ENV_DATA="".
- value: ''
-```
-
-### Ignoring resource updates configured in `ignoreDifferences` by default
-
-By default, the existing system-level `ignoreDifferences` customizations will be added to ignore resource updates as well.
-
-Logically, if differences to a field are configured to be ignored, there is no reason to generate the diff for the application
-when that field changes.
-
-To disable this behavior and preserve the v2 default, the `ignoreDifferencesOnResourceUpdates` can be set to false:
-
-```yaml
-apiVersion: v1
-kind: ConfigMap
-metadata:
- name: argocd-cm
-data:
- resource.compareoptions: |
- ignoreDifferencesOnResourceUpdates: false
-```
-
-More details for ignored resource updates in the [Reconcile Optimization](../reconcile.md) documentation.
-
-### Ignoring status field from differences by default
-
-By default, the compare options to ignore the status field has been changed from `crd` to `all` resources.
-
-This means that differences won't be detected anymore for fields that are part of the status.
-
-If you rely on the status field being part of your desired state, the `ignoreResourceStatusField` setting can be used to preserve the v2 default.
-
-```yaml
-apiVersion: v1
-kind: ConfigMap
-metadata:
- name: argocd-cm
-data:
- resource.compareoptions: |
- ignoreResourceStatusField: crd
-```
-
-### Removing default ignores of `preserveUnknownFields` for CRD
-
-The `spec.preserveUnknownFields` has been deprecated in favor of `x-kubernetes-preserve-unknown-fields: true` in the CRD v1.
-
-This means that CRD deployed with Argo CD containing `spec.preserveUnknownFields: false` will be out of sync. To address this problem,
-the `preserveUnknownFields` field can be removed from the CRD spec.
-
-Until this is completed, if you want your Application not to be out of sync, you can add the following configuration to the Application manifest.
-
-```yaml
-spec:
- ignoreDifferences:
- - group: apiextensions.k8s.io
- kind: CustomResourceDefinition
- jsonPointers:
- - /spec/preserveUnknownFields
-```
-
-You can also configure it globally in the `argocd-cm` ConfigMap.
-
-```yaml
-resource.customizations.ignoreDifferences.apiextensions.k8s.io_CustomResourceDefinition: |
- jsonPointers:
- - /spec/preserveUnknownFields
-```
-
-More details for ignored resource updates in the [Diffing customization](../../user-guide/diffing.md) documentation.
\ No newline at end of file
diff --git a/docs/operator-manual/upgrading/3.0-3.1.md b/docs/operator-manual/upgrading/3.0-3.1.md
deleted file mode 100644
index 408f46e8e0..0000000000
--- a/docs/operator-manual/upgrading/3.0-3.1.md
+++ /dev/null
@@ -1,7 +0,0 @@
-# v3.0 to 3.1
-
-## Symlink protection in API `--staticassets` directory
-
-The `--staticassets` directory in the API server (`/app/shared` by default) is now protected against out-of-bounds
-symlinks. This is to help protect against symlink attacks. If you have any symlinks in your `--staticassets` directory
-to a location outside the directory, they will return a 500 error starting with 3.1.
diff --git a/docs/operator-manual/upgrading/overview.md b/docs/operator-manual/upgrading/overview.md
index 4a6f710287..290ef05638 100644
--- a/docs/operator-manual/upgrading/overview.md
+++ b/docs/operator-manual/upgrading/overview.md
@@ -8,12 +8,12 @@
Argo CD uses semver-like versioning that ensures the following rules:
* The patch release does not introduce any breaking changes. So if you are upgrading from v1.5.1 to v1.5.3
- there should be no special instructions to follow.
+ there should be no special instructions to follow.
* The minor release might introduce minor changes with a workaround. If you are upgrading from v1.3.0 to v1.5.2
- please make sure to check upgrading details in both [v1.3 to v1.4](./1.3-1.4.md) and [v1.4 to v1.5](./1.4-1.5.md)
- upgrading instructions.
-* The major release introduces backward incompatible behavior changes. It is recommended to take a backup of
- Argo CD settings using disaster recovery [guide](../disaster_recovery.md).
+please make sure to check upgrading details in both [v1.3 to v1.4](./1.3-1.4.md) and [v1.4 to v1.5](./1.4-1.5.md)
+ upgrading instructions.
+ * The major release introduces backward incompatible behavior changes. It is recommended to take a backup of
+ Argo CD settings using disaster recovery [guide](../disaster_recovery.md).
After reading the relevant notes about possible breaking changes introduced in Argo CD version use the following
command to upgrade Argo CD. Make sure to replace `` with the required version number:
@@ -25,7 +25,6 @@ kubectl apply -n argocd -f https://raw.githubusercontent.com/argoproj/argo-cd//manifests/ha/install.yaml
```
@@ -38,8 +37,6 @@ kubectl apply -n argocd -f https://raw.githubusercontent.com/argoproj/argo-cd/
-* [v2.14 to v3.0](./2.14-3.0.md)
-* [v2.13 to v2.14](./2.13-2.14.md)
* [v2.12 to v2.13](./2.12-2.13.md)
* [v2.11 to v2.12](./2.11-2.12.md)
* [v2.10 to v2.11](./2.10-2.11.md)
diff --git a/docs/operator-manual/user-management/google.md b/docs/operator-manual/user-management/google.md
index a23becd591..366a1e9863 100644
--- a/docs/operator-manual/user-management/google.md
+++ b/docs/operator-manual/user-management/google.md
@@ -2,11 +2,11 @@
There are three different ways to integrate Argo CD login with your Google Workspace users. Generally the OpenID Connect (_oidc_) method would be the recommended way of doing this integration (and easier, as well...), but depending on your needs, you may choose a different option.
-- [OpenID Connect using Dex](#openid-connect-using-dex)
- This is the recommended login method if you don't need information about the groups the user's belongs to. Google doesn't expose the `groups` claim via _oidc_, so you won't be able to use Google Groups membership information for RBAC.
-- [SAML App Auth using Dex](#saml-app-auth-using-dex)
+* [OpenID Connect using Dex](#openid-connect-using-dex)
+ This is the recommended login method if you don't need information about the groups the user's belongs to. Google doesn't expose the `groups` claim via _oidc_, so you won't be able to use Google Groups membership information for RBAC.
+* [SAML App Auth using Dex](#saml-app-auth-using-dex)
Dex [recommends avoiding this method](https://dexidp.io/docs/connectors/saml/#warning). Also, you won't get Google Groups membership information through this method.
-- [OpenID Connect plus Google Groups using Dex](#openid-connect-plus-google-groups-using-dex)
+* [OpenID Connect plus Google Groups using Dex](#openid-connect-plus-google-groups-using-dex)
This is the recommended method if you need to use Google Groups membership in your RBAC configuration.
Once you've set up one of the above integrations, be sure to edit `argo-rbac-cm` to configure permissions (as in the example below). See [RBAC Configurations](../rbac.md) for more detailed scenarios.
@@ -27,7 +27,7 @@ data:
If you've never configured this, you'll be redirected straight to this if you try to create an OAuth Client ID
-1. Go to your [OAuth Consent](https://console.cloud.google.com/apis/credentials/consent) configuration. If you still haven't created one, select `Internal` or `External` and click `Create`
+1. Go to your [OAuth Consent](https://console.cloud.google.com/apis/credentials/consent) configuration. If you still haven't created one, select `Internal` or `External` and click `Create`
2. Go and [edit your OAuth consent screen](https://console.cloud.google.com/apis/credentials/consent/edit) Verify you're in the correct project!
3. Configure a name for your login app and a user support email address
4. The app logo and filling the information links is not mandatory, but it's a nice touch for the login page
@@ -44,7 +44,7 @@ If you've never configured this, you'll be redirected straight to this if you tr
4. Fill "Authorized JavaScript origins" with your Argo CD URL, e.g. `https://argocd.example.com`
5. Fill "Authorized redirect URIs" with your Argo CD URL plus `/api/dex/callback`, e.g. `https://argocd.example.com/api/dex/callback`
- 
+ 
6. Click "Create" and save your "Client ID" and your "Client Secret" for later
@@ -75,7 +75,6 @@ data:
### Configure a new SAML App
---
-
!!! warning "Deprecation Warning"
Note that, according to [Dex documentation](https://dexidp.io/docs/connectors/saml/#warning), SAML is considered unsafe and they are planning to deprecate that module.
@@ -84,32 +83,31 @@ data:
1. In the [Google admin console](https://admin.google.com), open the left-side menu and select `Apps` > `SAML Apps`
- 
+ 
2. Under `Add App` select `Add custom SAML app`
- 
+ 
3. Enter a `Name` for the application (e.g. `Argo CD`), then choose `Continue`
- 
+ 
4. Download the metadata or copy the `SSO URL`, `Certificate`, and optionally `Entity ID` from the identity provider details for use in the next section. Choose `continue`.
+ - Base64 encode the contents of the certificate file, for example:
+ - `$ cat ArgoCD.cer | base64`
+ - *Keep a copy of the encoded output to be used in the next section.*
+ - *Ensure that the certificate is in PEM format before base64 encoding*
- - Base64 encode the contents of the certificate file, for example:
- - `$ cat ArgoCD.cer | base64`
- - _Keep a copy of the encoded output to be used in the next section._
- - _Ensure that the certificate is in PEM format before base64 encoding_
-
- 
+ 
5. For both the `ACS URL` and `Entity ID`, use your Argo Dex Callback URL, for example: `https://argocd.example.com/api/dex/callback`
- 
+ 
6. Add SAML Attribute Mapping, Map `Primary email` to `name` and `Primary Email` to `email`. and click `ADD MAPPING` button.
- 
+ 
7. Finish creating the application.
@@ -148,9 +146,9 @@ We're going to use Dex's `google` connector to get additional Google Groups info
This connector uses two different credentials:
-- An oidc client ID and secret
+- An oidc client ID and secret
Same as when you're configuring an [OpenID connection](#openid-connect-using-dex), this authenticates your users
-- A Google service account
+- A Google service account
This is used to connect to the Google Directory API and pull information about your user's group membership
Also, you'll need the email address for an admin user on this domain. Dex will impersonate that user identity to fetch user information from the API.
@@ -159,96 +157,81 @@ Also, you'll need the email address for an admin user on this domain. Dex will i
Go through the same steps as in [OpenID Connect using Dex](#openid-connect-using-dex), except for configuring `argocd-cm`. We'll do that later.
-### Set up Directory API access
+### Set up Directory API access
1. Follow [Google instructions to create a service account with Domain-Wide Delegation](https://developers.google.com/admin-sdk/directory/v1/guides/delegation)
- - When assigning API scopes to the service account assign **only** the `https://www.googleapis.com/auth/admin.directory.group.readonly` scope and nothing else. If you assign any other scopes, you won't be able to fetch information from the API
- - Create the credentials in JSON format and store them in a safe place, we'll need them later
+ - When assigning API scopes to the service account assign **only** the `https://www.googleapis.com/auth/admin.directory.group.readonly` scope and nothing else. If you assign any other scopes, you won't be able to fetch information from the API
+ - Create the credentials in JSON format and store them in a safe place, we'll need them later
2. Enable the [Admin SDK](https://console.developers.google.com/apis/library/admin.googleapis.com/)
### Configure Dex
1. Create a secret with the contents of the previous json file encoded in base64, like this:
- ```yaml
- apiVersion: v1
- kind: Secret
- metadata:
- name: argocd-google-groups-json
- namespace: argocd
- data:
- googleAuth.json: JSON_FILE_BASE64_ENCODED
- ```
+ apiVersion: v1
+ kind: Secret
+ metadata:
+ name: argocd-google-groups-json
+ namespace: argocd
+ data:
+ googleAuth.json: JSON_FILE_BASE64_ENCODED
-2. Edit your `argocd-dex-server` deployment to mount that secret as a file
+2. Edit your `argocd-dex-server` deployment to mount that secret as a file
+ - Add a volume mount in `/spec/template/spec/containers/0/volumeMounts/` like this. Be aware of editing the running container and not the init container!
- - Add a volume mount in `/spec/template/spec/containers/0/volumeMounts/` like this. Be aware of editing the running container and not the init container!
+ volumeMounts:
+ - mountPath: /shared
+ name: static-files
+ - mountPath: /tmp
+ name: dexconfig
+ - mountPath: /tmp/oidc
+ name: google-json
+ readOnly: true
- ```yaml
- volumeMounts:
- - mountPath: /shared
- name: static-files
- - mountPath: /tmp
- name: dexconfig
- - mountPath: /tmp/oidc
- name: google-json
- readOnly: true
- ```
+ - Add a volume in `/spec/template/spec/volumes/` like this:
- - Add a volume in `/spec/template/spec/volumes/` like this:
+ volumes:
+ - emptyDir: {}
+ name: static-files
+ - emptyDir: {}
+ name: dexconfig
+ - name: google-json
+ secret:
+ defaultMode: 420
+ secretName: argocd-google-groups-json
- ```yaml
- volumes:
- - emptyDir: {}
- name: static-files
- - emptyDir: {}
- name: dexconfig
- - name: google-json
- secret:
- defaultMode: 420
- secretName: argocd-google-groups-json
- ```
+3. Edit `argocd-cm` and add the following `dex.config` to the data section, replacing `clientID` and `clientSecret` with the values you saved before, `adminEmail` with the address for the admin user you're going to impersonate, and editing `redirectURI` with your Argo CD domain (note that the `type` is now `google` instead of `oidc`):
-3. Edit `argocd-cm` and add the following `url` and `dex.config` to the data section, replacing `clientID` and `clientSecret` with the values you saved before, `adminEmail` with the address for the admin user you're going to impersonate, and editing `redirectURI` with your Argo CD domain (note that the `type` is now `google` instead of `oidc`):
-
- ```yaml
- data:
- url: https://argocd.example.com
- dex.config: |
- connectors:
- - config:
- redirectURI: https://argocd.example.com/api/dex/callback
- clientID: XXXXXXXXXXXXX.apps.googleusercontent.com
- clientSecret: XXXXXXXXXXXXX
- serviceAccountFilePath: /tmp/oidc/googleAuth.json
- adminEmail: admin-email@example.com
- type: google
- id: google
- name: Google
- ```
+ dex.config: |
+ connectors:
+ - config:
+ redirectURI: https://argocd.example.com/api/dex/callback
+ clientID: XXXXXXXXXXXXX.apps.googleusercontent.com
+ clientSecret: XXXXXXXXXXXXX
+ serviceAccountFilePath: /tmp/oidc/googleAuth.json
+ adminEmail: admin-email@example.com
+ type: google
+ id: google
+ name: Google
4. Restart your `argocd-dex-server` deployment to be sure it's using the latest configuration
-5. Login to Argo CD and go to the "User info" section, were you should see the groups you're member
- 
+5. Login to Argo CD and go to the "User info" section, were you should see the groups you're member
+ 
6. Now you can use groups email addresses to give RBAC permissions
-7. Dex (> v2.31.0) can also be configured in the `argocd-cm` to fetch transitive group membership as follows:
+7. Dex (> v2.31.0) can also be configure to fetch transitive group membership as follows:
- ```yaml
- data:
- url: https://argocd.example.com
- dex.config: |
- connectors:
- - config:
- redirectURI: https://argocd.example.com/api/dex/callback
- clientID: XXXXXXXXXXXXX.apps.googleusercontent.com
- clientSecret: XXXXXXXXXXXXX
- serviceAccountFilePath: /tmp/oidc/googleAuth.json
- adminEmail: admin-email@example.com
- fetchTransitiveGroupMembership: True
- type: google
- id: google
- name: Google
- ```
+ dex.config: |
+ connectors:
+ - config:
+ redirectURI: https://argocd.example.com/api/dex/callback
+ clientID: XXXXXXXXXXXXX.apps.googleusercontent.com
+ clientSecret: XXXXXXXXXXXXX
+ serviceAccountFilePath: /tmp/oidc/googleAuth.json
+ adminEmail: admin-email@example.com
+ fetchTransitiveGroupMembership: True
+ type: google
+ id: google
+ name: Google
### References
diff --git a/docs/operator-manual/user-management/identity-center.md b/docs/operator-manual/user-management/identity-center.md
index 62d381aec7..c4019964d7 100644
--- a/docs/operator-manual/user-management/identity-center.md
+++ b/docs/operator-manual/user-management/identity-center.md
@@ -10,15 +10,10 @@ A working Single Sign-On configuration using Identity Center (AWS SSO) has been
## SAML (with Dex)
1. Create a new SAML application in Identity Center and download the certificate.
-
-
-
-
-
+ * 
+ * 
2. Click `Assign Users` after creating the application in Identity Center, and select the users or user groups you wish to grant access to this application.
-
-
-
+ * 
3. Copy the Argo CD URL into the `data.url` field in the `argocd-cm` ConfigMap.
data:
@@ -29,20 +24,15 @@ A working Single Sign-On configuration using Identity Center (AWS SSO) has been
!!! note "Group attribute mapping is not officially!"
Group attribute mapping is not officially supported in the AWS docs, however the workaround is currently working.
-
-
-
+ * 
+ * 
5. Download the CA certificate to use in the `argocd-cm` configuration.
-
* If using the `caData` field, you'll need to base64-encode the entire certificate, including the `-----BEGIN CERTIFICATE-----` and `-----END CERTIFICATE-----` stanzas (e.g., `base64 my_cert.pem`).
-
* If using the `ca` field and storing the CA certificate separately as a secret, you will need to mount the secret onto the `dex` container in the `argocd-dex-server` Deployment.
-
-
-
+ * 
6. Edit the `argocd-cm` and configure the `data.dex.config` section:
@@ -70,7 +60,6 @@ dex.config: |
### Connect Identity Center Groups to Argo CD Roles
-
Argo CD recognizes user memberships in Identity Center groups that match the **Group Attribute Statements** regex.
In the example above, the regex `argocd-*` is used, making Argo CD aware of a group named `argocd-admins`.
diff --git a/docs/operator-manual/user-management/microsoft.md b/docs/operator-manual/user-management/microsoft.md
index ac431bdc78..72a3a3ce77 100644
--- a/docs/operator-manual/user-management/microsoft.md
+++ b/docs/operator-manual/user-management/microsoft.md
@@ -3,127 +3,10 @@
!!! note ""
Entra ID was formerly known as Azure AD.
-* [Entra ID App Registration Auth using OIDC](#entra-id-app-registration-auth-using-oidc)
* [Entra ID SAML Enterprise App Auth using Dex](#entra-id-saml-enterprise-app-auth-using-dex)
+* [Entra ID App Registration Auth using OIDC](#entra-id-app-registration-auth-using-oidc)
* [Entra ID App Registration Auth using Dex](#entra-id-app-registration-auth-using-dex)
-## Entra ID App Registration Auth using OIDC
-### Configure a new Entra ID App registration
-#### Add a new Entra ID App registration
-
-1. From the `Microsoft Entra ID` > `App registrations` menu, choose `+ New registration`
-2. Enter a `Name` for the application (e.g. `Argo CD`).
-3. Specify who can use the application (e.g. `Accounts in this organizational directory only`).
-4. Enter Redirect URI (optional) as follows (replacing `my-argo-cd-url` with your Argo URL), then choose `Add`.
- - **Platform:** `Web`
- - **Redirect URI:** https://``/auth/callback
-5. When registration finishes, the Azure portal displays the app registration's Overview pane. You see the Application (client) ID.
- 
-
-#### Configure additional platform settings for ArgoCD CLI
-
-1. In the Azure portal, in App registrations, select your application.
-2. Under Manage, select Authentication.
-3. Under Platform configurations, select Add a platform.
-4. Under Configure platforms, select the "Mobile and desktop applications" tile. Use the below value. You shouldn't change it.
- - **Redirect URI:** `http://localhost:8085/auth/callback`
- 
-
-#### Add credentials a new Entra ID App registration
-##### Using Workload Identity Federation (Recommended)
-1. **Label the Pods:** Add the `azure.workload.identity/use: "true"` label to the `argocd-server` pods.
-2. **Add Annotation to Service Account:** Add `azure.workload.identity/client-id: "$CLIENT_ID"` annotation to the `argocd-server` service account using the details from application created in previous step.
-3. From the `Certificates & secrets` menu, navigate to `Federated credentials`, then choose `+ Add credential`
-4. Choose `Federated credential scenario` as `Kubernetes Accessing Azure resources`
- - Enter Cluster Issuer URL, refer to [retrieve the OIDC issuer URL](https://learn.microsoft.com/en-us/azure/aks/workload-identity-deploy-cluster#retrieve-the-oidc-issuer-url) documentation
- - Enter namespace as the namespace where the argocd is deployed
- - Enter service account name as `argocd-server`
- - Enter a unique name
- - Click Add.
-
-##### Using Client Secret
-1. From the `Certificates & secrets` menu, choose `+ New client secret`
-2. Enter a `Name` for the secret (e.g. `ArgoCD-SSO`).
- - Make sure to copy and save generated value. This is a value for the `client_secret`.
- 
-
-#### Setup permissions for Entra ID Application
-
-1. From the `API permissions` menu, choose `+ Add a permission`
-2. Find `User.Read` permission (under `Microsoft Graph`) and grant it to the created application:
- 
-3. From the `Token Configuration` menu, choose `+ Add groups claim`
- 
-
-### Associate an Entra ID group to your Entra ID App registration
-
-1. From the `Microsoft Entra ID` > `Enterprise applications` menu, search the App that you created (e.g. `Argo CD`).
- - An Enterprise application with the same name of the Entra ID App registration is created when you add a new Entra ID App registration.
-2. From the `Users and groups` menu of the app, add any users or groups requiring access to the service.
- 
-
-### Configure Argo to use the new Entra ID App registration
-
-1. Edit `argocd-cm` and configure the `data.oidc.config` and `data.url` section:
-
- ConfigMap -> argocd-cm
-
- data:
- url: https://argocd.example.com/ # Replace with the external base URL of your Argo CD
- oidc.config: |
- name: Azure
- issuer: https://login.microsoftonline.com/{directory_tenant_id}/v2.0
- clientID: {azure_ad_application_client_id}
- clientSecret: $oidc.azure.clientSecret // if using client secret for authentication
- azure:
- useWorkloadIdentity: true // if using azure workload identity for authentication
- requestedIDTokenClaims:
- groups:
- essential: true
- value: "SecurityGroup"
- requestedScopes:
- - openid
- - profile
- - email
-
-2. Skip this step if using azure workload identity. Edit `argocd-secret` and configure the `data.oidc.azure.clientSecret` section:
-
- Secret -> argocd-secret
-
- data:
- oidc.azure.clientSecret: {client_secret | base64_encoded}
-
-3. Edit `argocd-rbac-cm` to configure permissions. Use group ID from Azure for assigning roles
- [RBAC Configurations](../rbac.md)
-
- ConfigMap -> argocd-rbac-cm
-
- policy.default: role:readonly
- policy.csv: |
- p, role:org-admin, applications, *, */*, allow
- p, role:org-admin, clusters, get, *, allow
- p, role:org-admin, repositories, get, *, allow
- p, role:org-admin, repositories, create, *, allow
- p, role:org-admin, repositories, update, *, allow
- p, role:org-admin, repositories, delete, *, allow
- g, "84ce98d1-e359-4f3b-85af-985b458de3c6", role:org-admin
-
-4. Mapping role from jwt token to argo.
- If you want to map the roles from the jwt token to match the default roles (readonly and admin) then you must change the scope variable in the rbac-configmap.
-
- policy.default: role:readonly
- policy.csv: |
- p, role:org-admin, applications, *, */*, allow
- p, role:org-admin, clusters, get, *, allow
- p, role:org-admin, repositories, get, *, allow
- p, role:org-admin, repositories, create, *, allow
- p, role:org-admin, repositories, update, *, allow
- p, role:org-admin, repositories, delete, *, allow
- g, "84ce98d1-e359-4f3b-85af-985b458de3c6", role:org-admin
- scopes: '[groups, email]'
-
- Refer to [operator-manual/argocd-rbac-cm.yaml](https://github.com/argoproj/argo-cd/blob/master/docs/operator-manual/argocd-rbac-cm.yaml) for all of the available variables.
-
## Entra ID SAML Enterprise App Auth using Dex
### Configure a new Entra ID Enterprise App
@@ -190,6 +73,110 @@
p, role:org-admin, repositories, delete, *, allow
g, "84ce98d1-e359-4f3b-85af-985b458de3c6", role:org-admin # (azure group assigned to role)
+## Entra ID App Registration Auth using OIDC
+### Configure a new Entra ID App registration
+#### Add a new Entra ID App registration
+
+1. From the `Microsoft Entra ID` > `App registrations` menu, choose `+ New registration`
+2. Enter a `Name` for the application (e.g. `Argo CD`).
+3. Specify who can use the application (e.g. `Accounts in this organizational directory only`).
+4. Enter Redirect URI (optional) as follows (replacing `my-argo-cd-url` with your Argo URL), then choose `Add`.
+ - **Platform:** `Web`
+ - **Redirect URI:** https://``/auth/callback
+5. When registration finishes, the Azure portal displays the app registration's Overview pane. You see the Application (client) ID.
+ 
+
+#### Configure additional platform settings for ArgoCD CLI
+
+1. In the Azure portal, in App registrations, select your application.
+2. Under Manage, select Authentication.
+3. Under Platform configurations, select Add a platform.
+4. Under Configure platforms, select the "Mobile and desktop applications" tile. Use the below value. You shouldn't change it.
+ - **Redirect URI:** `http://localhost:8085/auth/callback`
+ 
+
+#### Add credentials a new Entra ID App registration
+
+1. From the `Certificates & secrets` menu, choose `+ New client secret`
+2. Enter a `Name` for the secret (e.g. `ArgoCD-SSO`).
+ - Make sure to copy and save generated value. This is a value for the `client_secret`.
+ 
+
+#### Setup permissions for Entra ID Application
+
+1. From the `API permissions` menu, choose `+ Add a permission`
+2. Find `User.Read` permission (under `Microsoft Graph`) and grant it to the created application:
+ 
+3. From the `Token Configuration` menu, choose `+ Add groups claim`
+ 
+
+### Associate an Entra ID group to your Entra ID App registration
+
+1. From the `Microsoft Entra ID` > `Enterprise applications` menu, search the App that you created (e.g. `Argo CD`).
+ - An Enterprise application with the same name of the Entra ID App registration is created when you add a new Entra ID App registration.
+2. From the `Users and groups` menu of the app, add any users or groups requiring access to the service.
+ 
+
+### Configure Argo to use the new Entra ID App registration
+
+1. Edit `argocd-cm` and configure the `data.oidc.config` and `data.url` section:
+
+ ConfigMap -> argocd-cm
+
+ data:
+ url: https://argocd.example.com/ # Replace with the external base URL of your Argo CD
+ oidc.config: |
+ name: Azure
+ issuer: https://login.microsoftonline.com/{directory_tenant_id}/v2.0
+ clientID: {azure_ad_application_client_id}
+ clientSecret: $oidc.azure.clientSecret
+ requestedIDTokenClaims:
+ groups:
+ essential: true
+ value: "SecurityGroup"
+ requestedScopes:
+ - openid
+ - profile
+ - email
+
+2. Edit `argocd-secret` and configure the `data.oidc.azure.clientSecret` section:
+
+ Secret -> argocd-secret
+
+ data:
+ oidc.azure.clientSecret: {client_secret | base64_encoded}
+
+3. Edit `argocd-rbac-cm` to configure permissions. Use group ID from Azure for assigning roles
+ [RBAC Configurations](../rbac.md)
+
+ ConfigMap -> argocd-rbac-cm
+
+ policy.default: role:readonly
+ policy.csv: |
+ p, role:org-admin, applications, *, */*, allow
+ p, role:org-admin, clusters, get, *, allow
+ p, role:org-admin, repositories, get, *, allow
+ p, role:org-admin, repositories, create, *, allow
+ p, role:org-admin, repositories, update, *, allow
+ p, role:org-admin, repositories, delete, *, allow
+ g, "84ce98d1-e359-4f3b-85af-985b458de3c6", role:org-admin
+
+4. Mapping role from jwt token to argo.
+ If you want to map the roles from the jwt token to match the default roles (readonly and admin) then you must change the scope variable in the rbac-configmap.
+
+ policy.default: role:readonly
+ policy.csv: |
+ p, role:org-admin, applications, *, */*, allow
+ p, role:org-admin, clusters, get, *, allow
+ p, role:org-admin, repositories, get, *, allow
+ p, role:org-admin, repositories, create, *, allow
+ p, role:org-admin, repositories, update, *, allow
+ p, role:org-admin, repositories, delete, *, allow
+ g, "84ce98d1-e359-4f3b-85af-985b458de3c6", role:org-admin
+ scopes: '[groups, email]'
+
+ Refer to [operator-manual/argocd-rbac-cm.yaml](https://github.com/argoproj/argo-cd/blob/master/docs/operator-manual/argocd-rbac-cm.yaml) for all of the available variables.
+
## Entra ID App Registration Auth using Dex
Configure a new AD App Registration, as above.
diff --git a/docs/operator-manual/webhook.md b/docs/operator-manual/webhook.md
index d042fc7be9..f57918583e 100644
--- a/docs/operator-manual/webhook.md
+++ b/docs/operator-manual/webhook.md
@@ -109,17 +109,3 @@ Syntax: `$:`
> NOTE: Secret must have label `app.kubernetes.io/part-of: argocd`
For more information refer to the corresponding section in the [User Management Documentation](user-management/index.md#alternative).
-
-## Special handling for BitBucket Cloud
-BitBucket does not include the list of changed files in the webhook request body.
-This prevents the [Manifest Paths Annotation](high_availability.md#manifest-paths-annotation) feature from working with repositories hosted on BitBucket Cloud.
-BitBucket provides the `diffstat` API to determine the list of changed files between two commits.
-To address the missing changed files list in the webhook, the Argo CD webhook handler makes an API callback to the originating server.
-To prevent Server-side request forgery (SSRF) attacks, Argo CD server supports the callback mechanism only for encrypted webhook requests.
-The incoming webhook must include `X-Hook-UUID` request header. The corresponding UUID must be provided as `webhook.bitbucket.uuid` in `argocd-secret` for verification.
-The callback mechanism supports both public and private repositories on BitBucket Cloud.
-For public repositories, the Argo CD webhook handler uses a no-auth client for the API callback.
-For private repositories, the Argo CD webhook handler searches for a valid repository OAuth token for the HTTP/HTTPS URL.
-The webhook handler uses this OAuth token to make the API request to the originating server.
-If the Argo CD webhook handler cannot find a matching repository credential, the list of changed files would remain empty.
-If errors occur during the callback, the list of changed files will be empty.
\ No newline at end of file
diff --git a/docs/proposals/argocd-cli-pluin.md b/docs/proposals/argocd-cli-pluin.md
deleted file mode 100644
index 4f38f22388..0000000000
--- a/docs/proposals/argocd-cli-pluin.md
+++ /dev/null
@@ -1,54 +0,0 @@
----
-title: Argo CD CLI Plugin
-authors:
- - "@christianh814"
- - "@alexmt"
- - "@nitishfy"
-
-sponsors:
- - TBD
-reviewers:
- - TBD
-approvers:
- - TBD
-
-creation-date: 2024-08-21
----
-
-# Argo CD CLI Plugin Support
-
-Support for `kubectl`-like plugins for the `argocd` CLI.
-
-## Summary
-
-Enhance the Argo CD `argocd` CLI client to support the ability to provide other CLI tools as "plugins" in a similar way that the Kubernetes `kubectl` CLI client provides. This will shift `argocd` to be more of a "building block" or "interface" for interacting with Argo CD and plugins can be a means to develop more complex workflows while leaving the baseline argocd use-case small.
-
-## Motivation
-
-Currently, the `argocd` CLI client is-getting/already-is pretty bloated. The solution has either been written-in the support for certain solutions (like ApplicationSets) or having a separate CLI tool in Argo Project Labs (like [Autopilot](https://github.com/argoproj-labs/argocd-autopilot) and [Vault Plugin](https://github.com/argoproj-labs/argocd-vault-plugin)).
-
-Having a plugin system makes sense, as we add more and more features down the line (OCI, Hydrator, GitOps Promoter, etc). In this way, we can keep the `argocd` CLI "lean" but also extensible and keep things "out of tree". As mentioned before, other tools that can benefit from this besides the Argo CD OCI cli is a tool like `argocd-autopilot`. Also, there is a potential for other Argo Project tools to have plugins, like a Rollouts plugin or an `argocd-image-updater` plugin for Argo CD.
-
-The idea initially came up during a discussion about [adding CLI support for the upcoming OCI integration](https://cloud-native.slack.com/archives/C06Q17QJPJR/p1721227926706059?thread_ts=1720731234.357799&cid=C06Q17QJPJR).
-
-## Goals
-
-The goal is to provide a plugin mechanism without changing the current behavior of `argocd`'s subcommands and options.
-
-## Non Goals
-
-Make any guarantees for any public `argocd` plugins provided by any third party.
-
-## Proposal
-
-Similarly to how `kubectl` plugins are handled, The `argocd` CLI tool will look in the end user's `$PATH` for any binaries that start with `argocd-` and execute that binary. For example if I had a binary called `argocd-mytool` in my `$PATH`, I could call it by running `argocd mytool`. Support for tab completion should also be taken into account.
-
-## Outstanding Questions
-
-Things to consider:
-
-* Should it act exactly like `kubectl` and just look in `$PATH` or be more stringent and have users store plugins in `~/.config/argocd/plugins`? Similar to [Tekton plugins](https://tekton.dev/vault/cli-main/tkn-plugins/#location)
-* Is there a way to integrate this with [Krew](https://krew.sigs.k8s.io/) for installing plugins?
-* Should we let each plugin manage its own configuration settings or make plugins use `~/.config/argocd/config` and provide a new field called `.pluginConfigs`? For example the `argocd-mytool` plugin's config will be under `.pluginConfigs.mytool` Should we even care/have an opinion?
-* Should we provide any guidelines to submit a plugin? Do we only "accept" plugins that are in argoproj-labs?
-
diff --git a/docs/requirements.txt b/docs/requirements.txt
index ff7dc98ae0..ad1dcf32ff 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.1
-jinja2==3.1.6
-markdown==3.8
-pymdown-extensions==10.15
\ No newline at end of file
+pygments==2.18.0
+jinja2==3.1.4
+markdown==3.7
+pymdown-extensions==10.12
\ No newline at end of file
diff --git a/docs/snyk/index.md b/docs/snyk/index.md
index 8a004c4832..586bbaf6a7 100644
--- a/docs/snyk/index.md
+++ b/docs/snyk/index.md
@@ -14,53 +14,52 @@ recent minor releases.
| | Critical | High | Medium | Low |
|---:|:--------:|:----:|:------:|:---:|
| [go.mod](master/argocd-test.html) | 0 | 0 | 6 | 0 |
-| [ui/yarn.lock](master/argocd-test.html) | 0 | 1 | 1 | 2 |
-| [dex:v2.41.1](master/ghcr.io_dexidp_dex_v2.41.1.html) | 0 | 0 | 0 | 5 |
-| [haproxy:3.0.8-alpine](master/public.ecr.aws_docker_library_haproxy_3.0.8-alpine.html) | 0 | 0 | 0 | 0 |
-| [redis:7.2.7-alpine](master/public.ecr.aws_docker_library_redis_7.2.7-alpine.html) | 0 | 0 | 0 | 0 |
-| [argocd:latest](master/quay.io_argoproj_argocd_latest.html) | 0 | 0 | 4 | 8 |
-| [redis:7.2.7-alpine](master/redis_7.2.7-alpine.html) | 0 | 0 | 0 | 0 |
+| [ui/yarn.lock](master/argocd-test.html) | 0 | 0 | 1 | 0 |
+| [dex:v2.41.1](master/ghcr.io_dexidp_dex_v2.41.1.html) | 0 | 0 | 0 | 2 |
+| [haproxy:2.6.17-alpine](master/public.ecr.aws_docker_library_haproxy_2.6.17-alpine.html) | 0 | 0 | 2 | 4 |
+| [redis:7.0.15-alpine](master/public.ecr.aws_docker_library_redis_7.0.15-alpine.html) | 0 | 0 | 0 | 1 |
+| [argocd:latest](master/quay.io_argoproj_argocd_latest.html) | 0 | 0 | 3 | 10 |
+| [redis:7.0.15-alpine](master/redis_7.0.15-alpine.html) | 0 | 0 | 0 | 1 |
| [install.yaml](master/argocd-iac-install.html) | - | - | - | - |
| [namespace-install.yaml](master/argocd-iac-namespace-install.html) | - | - | - | - |
-### v2.14.5
+### v2.13.2
| | Critical | High | Medium | Low |
|---:|:--------:|:----:|:------:|:---:|
-| [go.mod](v2.14.5/argocd-test.html) | 0 | 4 | 9 | 0 |
-| [ui/yarn.lock](v2.14.5/argocd-test.html) | 0 | 1 | 1 | 2 |
-| [dex:v2.41.1](v2.14.5/ghcr.io_dexidp_dex_v2.41.1.html) | 0 | 0 | 0 | 5 |
-| [haproxy:2.6.17-alpine](v2.14.5/public.ecr.aws_docker_library_haproxy_2.6.17-alpine.html) | 0 | 0 | 2 | 7 |
-| [redis:7.0.15-alpine](v2.14.5/public.ecr.aws_docker_library_redis_7.0.15-alpine.html) | 0 | 0 | 0 | 4 |
-| [argocd:v2.14.5](v2.14.5/quay.io_argoproj_argocd_v2.14.5.html) | 0 | 0 | 4 | 8 |
-| [redis:7.0.15-alpine](v2.14.5/redis_7.0.15-alpine.html) | 0 | 0 | 0 | 4 |
-| [install.yaml](v2.14.5/argocd-iac-install.html) | - | - | - | - |
-| [namespace-install.yaml](v2.14.5/argocd-iac-namespace-install.html) | - | - | - | - |
+| [go.mod](v2.13.2/argocd-test.html) | 1 | 0 | 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 | 10 |
+| [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) | - | - | - | - |
-### v2.13.5
+### v2.12.8
| | Critical | High | Medium | Low |
|---:|:--------:|:----:|:------:|:---:|
-| [go.mod](v2.13.5/argocd-test.html) | 0 | 3 | 9 | 2 |
-| [ui/yarn.lock](v2.13.5/argocd-test.html) | 0 | 1 | 1 | 2 |
-| [dex:v2.41.1](v2.13.5/ghcr.io_dexidp_dex_v2.41.1.html) | 0 | 0 | 0 | 5 |
-| [haproxy:2.6.17-alpine](v2.13.5/public.ecr.aws_docker_library_haproxy_2.6.17-alpine.html) | 0 | 0 | 2 | 7 |
-| [redis:7.0.15-alpine](v2.13.5/public.ecr.aws_docker_library_redis_7.0.15-alpine.html) | 0 | 0 | 0 | 4 |
-| [argocd:v2.13.5](v2.13.5/quay.io_argoproj_argocd_v2.13.5.html) | 0 | 0 | 12 | 12 |
-| [redis:7.0.15-alpine](v2.13.5/redis_7.0.15-alpine.html) | 0 | 0 | 0 | 4 |
-| [install.yaml](v2.13.5/argocd-iac-install.html) | - | - | - | - |
-| [namespace-install.yaml](v2.13.5/argocd-iac-namespace-install.html) | - | - | - | - |
+| [go.mod](v2.12.8/argocd-test.html) | 1 | 0 | 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 | 10 |
+| [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) | - | - | - | - |
-### v2.12.10
+### v2.11.12
| | Critical | High | Medium | Low |
|---:|:--------:|:----:|:------:|:---:|
-| [go.mod](v2.12.10/argocd-test.html) | 0 | 2 | 9 | 2 |
-| [ui/yarn.lock](v2.12.10/argocd-test.html) | 0 | 1 | 1 | 2 |
-| [dex:v2.38.0](v2.12.10/ghcr.io_dexidp_dex_v2.38.0.html) | 0 | 0 | 6 | 9 |
-| [haproxy:2.6.17-alpine](v2.12.10/public.ecr.aws_docker_library_haproxy_2.6.17-alpine.html) | 0 | 0 | 2 | 7 |
-| [redis:7.0.15-alpine](v2.12.10/public.ecr.aws_docker_library_redis_7.0.15-alpine.html) | 0 | 0 | 0 | 4 |
-| [argocd:v2.12.10](v2.12.10/quay.io_argoproj_argocd_v2.12.10.html) | 0 | 0 | 13 | 12 |
-| [redis:7.0.15-alpine](v2.12.10/redis_7.0.15-alpine.html) | 0 | 0 | 0 | 4 |
-| [install.yaml](v2.12.10/argocd-iac-install.html) | - | - | - | - |
-| [namespace-install.yaml](v2.12.10/argocd-iac-namespace-install.html) | - | - | - | - |
+| [go.mod](v2.11.12/argocd-test.html) | 1 | 2 | 9 | 2 |
+| [ui/yarn.lock](v2.11.12/argocd-test.html) | 0 | 0 | 1 | 0 |
+| [dex:v2.38.0](v2.11.12/ghcr.io_dexidp_dex_v2.38.0.html) | 0 | 0 | 6 | 7 |
+| [haproxy:2.6.14-alpine](v2.11.12/haproxy_2.6.14-alpine.html) | 0 | 1 | 7 | 7 |
+| [argocd:v2.11.12](v2.11.12/quay.io_argoproj_argocd_v2.11.12.html) | 0 | 0 | 4 | 20 |
+| [redis:7.0.15-alpine](v2.11.12/redis_7.0.15-alpine.html) | 0 | 0 | 0 | 1 |
+| [install.yaml](v2.11.12/argocd-iac-install.html) | - | - | - | - |
+| [namespace-install.yaml](v2.11.12/argocd-iac-namespace-install.html) | - | - | - | - |
diff --git a/docs/snyk/master/argocd-iac-install.html b/docs/snyk/master/argocd-iac-install.html
index 700f094e1e..5c580258ab 100644
--- a/docs/snyk/master/argocd-iac-install.html
+++ b/docs/snyk/master/argocd-iac-install.html
@@ -456,7 +456,7 @@
Scanned the following path:
@@ -507,7 +507,7 @@
- Line number: 24296
+ Line number: 22859
@@ -553,7 +553,7 @@
- Line number: 23976
+ Line number: 22540
@@ -599,7 +599,7 @@
- Line number: 24064
+ Line number: 22627
@@ -645,7 +645,7 @@
- Line number: 24092
+ Line number: 22655
@@ -691,7 +691,7 @@
- Line number: 24122
+ Line number: 22685
@@ -737,7 +737,7 @@
- Line number: 24140
+ Line number: 22703
@@ -783,7 +783,7 @@
- Line number: 24158
+ Line number: 22721
@@ -829,7 +829,7 @@
- Line number: 24180
+ Line number: 22743
@@ -881,7 +881,7 @@
- Line number: 25386
+ Line number: 23833
@@ -933,7 +933,7 @@
- Line number: 25705
+ Line number: 24140
@@ -991,7 +991,7 @@
- Line number: 24887
+ Line number: 23352
@@ -1049,7 +1049,7 @@
- Line number: 25182
+ Line number: 23635
@@ -1107,7 +1107,7 @@
- Line number: 25130
+ Line number: 23589
@@ -1165,7 +1165,7 @@
- Line number: 25244
+ Line number: 23697
@@ -1223,7 +1223,7 @@
- Line number: 25357
+ Line number: 23804
@@ -1281,7 +1281,7 @@
- Line number: 25381
+ Line number: 23828
@@ -1339,7 +1339,7 @@
- Line number: 25705
+ Line number: 24140
@@ -1397,7 +1397,7 @@
- Line number: 25440
+ Line number: 23887
@@ -1455,7 +1455,7 @@
- Line number: 25792
+ Line number: 24227
@@ -1513,7 +1513,7 @@
- Line number: 26202
+ Line number: 24619
@@ -1565,7 +1565,7 @@
- Line number: 25162
+ Line number: 23615
@@ -1617,7 +1617,7 @@
- Line number: 24887
+ Line number: 23352
@@ -1669,7 +1669,7 @@
- Line number: 25130
+ Line number: 23589
@@ -1721,7 +1721,7 @@
- Line number: 25357
+ Line number: 23804
@@ -1779,7 +1779,7 @@
- Line number: 24887
+ Line number: 23352
@@ -1837,7 +1837,7 @@
- Line number: 25130
+ Line number: 23589
@@ -1895,7 +1895,7 @@
- Line number: 25182
+ Line number: 23635
@@ -1953,7 +1953,7 @@
- Line number: 25244
+ Line number: 23697
@@ -2011,7 +2011,7 @@
- Line number: 25357
+ Line number: 23804
@@ -2069,7 +2069,7 @@
- Line number: 25381
+ Line number: 23828
@@ -2127,7 +2127,7 @@
- Line number: 25705
+ Line number: 24140
@@ -2185,7 +2185,7 @@
- Line number: 25440
+ Line number: 23887
@@ -2243,7 +2243,7 @@
- Line number: 25792
+ Line number: 24227
@@ -2301,7 +2301,7 @@
- Line number: 26202
+ Line number: 24619
@@ -2357,7 +2357,7 @@
- Line number: 25052
+ Line number: 23511
@@ -2413,7 +2413,7 @@
- Line number: 25190
+ Line number: 23643
@@ -2469,7 +2469,7 @@
- Line number: 25165
+ Line number: 23618
@@ -2525,7 +2525,7 @@
- Line number: 25289
+ Line number: 23736
@@ -2581,7 +2581,7 @@
- Line number: 25374
+ Line number: 23821
@@ -2637,7 +2637,7 @@
- Line number: 25388
+ Line number: 23835
@@ -2693,7 +2693,7 @@
- Line number: 25712
+ Line number: 24147
@@ -2749,7 +2749,7 @@
- Line number: 25678
+ Line number: 24113
@@ -2805,7 +2805,7 @@
- Line number: 26101
+ Line number: 24518
@@ -2861,7 +2861,7 @@
- Line number: 26459
+ Line number: 24846
diff --git a/docs/snyk/master/argocd-iac-namespace-install.html b/docs/snyk/master/argocd-iac-namespace-install.html
index a6370f91f4..acfee91c34 100644
--- a/docs/snyk/master/argocd-iac-namespace-install.html
+++ b/docs/snyk/master/argocd-iac-namespace-install.html
@@ -456,7 +456,7 @@
Scanned the following path:
@@ -553,7 +553,7 @@
- Line number: 165
+ Line number: 164
@@ -599,7 +599,7 @@
- Line number: 193
+ Line number: 192
@@ -645,7 +645,7 @@
- Line number: 223
+ Line number: 222
@@ -691,7 +691,7 @@
- Line number: 241
+ Line number: 240
@@ -737,7 +737,7 @@
- Line number: 259
+ Line number: 258
@@ -783,7 +783,7 @@
- Line number: 281
+ Line number: 280
@@ -835,7 +835,7 @@
- Line number: 1273
+ Line number: 1156
@@ -887,7 +887,7 @@
- Line number: 1592
+ Line number: 1463
@@ -945,7 +945,7 @@
- Line number: 774
+ Line number: 675
@@ -1003,7 +1003,7 @@
- Line number: 1069
+ Line number: 958
@@ -1061,7 +1061,7 @@
- Line number: 1017
+ Line number: 912
@@ -1119,7 +1119,7 @@
- Line number: 1131
+ Line number: 1020
@@ -1177,7 +1177,7 @@
- Line number: 1244
+ Line number: 1127
@@ -1235,7 +1235,7 @@
- Line number: 1268
+ Line number: 1151
@@ -1293,7 +1293,7 @@
- Line number: 1592
+ Line number: 1463
@@ -1351,7 +1351,7 @@
- Line number: 1327
+ Line number: 1210
@@ -1409,7 +1409,7 @@
- Line number: 1679
+ Line number: 1550
@@ -1467,7 +1467,7 @@
- Line number: 2089
+ Line number: 1942
@@ -1519,7 +1519,7 @@
- Line number: 1049
+ Line number: 938
@@ -1571,7 +1571,7 @@
- Line number: 774
+ Line number: 675
@@ -1623,7 +1623,7 @@
- Line number: 1017
+ Line number: 912
@@ -1675,7 +1675,7 @@
- Line number: 1244
+ Line number: 1127
@@ -1733,7 +1733,7 @@
- Line number: 774
+ Line number: 675
@@ -1791,7 +1791,7 @@
- Line number: 1017
+ Line number: 912
@@ -1849,7 +1849,7 @@
- Line number: 1069
+ Line number: 958
@@ -1907,7 +1907,7 @@
- Line number: 1131
+ Line number: 1020
@@ -1965,7 +1965,7 @@
- Line number: 1244
+ Line number: 1127
@@ -2023,7 +2023,7 @@
- Line number: 1268
+ Line number: 1151
@@ -2081,7 +2081,7 @@
- Line number: 1592
+ Line number: 1463
@@ -2139,7 +2139,7 @@
- Line number: 1327
+ Line number: 1210
@@ -2197,7 +2197,7 @@
- Line number: 1679
+ Line number: 1550
@@ -2255,7 +2255,7 @@
- Line number: 2089
+ Line number: 1942
@@ -2311,7 +2311,7 @@
- Line number: 939
+ Line number: 834
@@ -2367,7 +2367,7 @@
- Line number: 1077
+ Line number: 966
@@ -2423,7 +2423,7 @@
- Line number: 1052
+ Line number: 941
@@ -2479,7 +2479,7 @@
- Line number: 1176
+ Line number: 1059
@@ -2535,7 +2535,7 @@
- Line number: 1261
+ Line number: 1144
@@ -2591,7 +2591,7 @@
- Line number: 1275
+ Line number: 1158
@@ -2647,7 +2647,7 @@
- Line number: 1599
+ Line number: 1470
@@ -2703,7 +2703,7 @@
- Line number: 1565
+ Line number: 1436
@@ -2759,7 +2759,7 @@
- Line number: 1988
+ Line number: 1841
@@ -2815,7 +2815,7 @@
- Line number: 2346
+ Line number: 2169
diff --git a/docs/snyk/master/argocd-test.html b/docs/snyk/master/argocd-test.html
index 878aae9971..6f8eea772a 100644
--- a/docs/snyk/master/argocd-test.html
+++ b/docs/snyk/master/argocd-test.html
@@ -7,7 +7,7 @@
Snyk test report
-
+
@@ -456,21 +456,21 @@
Scanned the following paths:
- /argo-cd/argoproj/argo-cd/v3/go.mod (gomodules)
+ /argo-cd/argoproj/argo-cd/v2/go.mod (gomodules)
/argo-cd/argoproj/argo-cd/get-previous-release/hack/get-previous-release/go.mod (gomodules)
/argo-cd/ui/yarn.lock (yarn)
@@ -478,172 +478,6 @@
-
-
Prototype Pollution
-
-
-
- high severity
-
-
-
-
-
-
-
-
-
-
Detailed paths
-
-
-
-
-
-
-
-
Overview
-
redoc is an OpenAPI/Swagger-generated API Reference Documentation.
-
Affected versions of this package are vulnerable to Prototype Pollution via the mergeObjects() method in utils/helpers.ts due to improper user input sanitization.
-
PoC
-
(async () => {
- const lib = await import('redoc');
-
- var BAD_JSON = JSON.parse('{"__proto__":{"polluted":true}}');
- var victim = {}
- console.log("Before Attack: ", JSON.stringify(victim.__proto__));
- try {
- lib.mergeObjects ({}, BAD_JSON)
- } catch (e) { }
- console.log("After Attack: ", JSON.stringify(victim.__proto__));
- delete Object.prototype.polluted;
- })();
-
-
Details
-
Prototype Pollution is a vulnerability affecting JavaScript. Prototype Pollution refers to the ability to inject properties into existing JavaScript language construct prototypes, such as objects. JavaScript allows all Object attributes to be altered, including their magical attributes such as __proto__, constructor and prototype. An attacker manipulates these attributes to overwrite, or pollute, a JavaScript application object prototype of the base object by injecting other values. Properties on the Object.prototype are then inherited by all the JavaScript objects through the prototype chain. When that happens, this leads to either denial of service by triggering JavaScript exceptions, or it tampers with the application source code to force the code path that the attacker injects, thereby leading to remote code execution.
-
There are two main ways in which the pollution of prototypes occurs:
-
-
Unsafe Object recursive merge
-
The logic of a vulnerable recursive merge function follows the following high-level model:
-
merge (target, source)
-
- foreach property of source
-
- if property exists and is an object on both the target and the source
-
- merge(target[property], source[property])
-
- else
-
- target[property] = source[property]
-
-
-
-
When the source object contains a property named __proto__ defined with Object.defineProperty() , the condition that checks if the property exists and is an object on both the target and the source passes and the merge recurses with the target, being the prototype of Object and the source of Object as defined by the attacker. Properties are then copied on the Object prototype.
-
Clone operations are a special sub-class of unsafe recursive merges, which occur when a recursive merge is conducted on an empty object: merge({},source).
-
lodash and Hoek are examples of libraries susceptible to recursive merge attacks.
-
Property definition by path
-
There are a few JavaScript libraries that use an API to define property values on an object based on a given path. The function that is generally affected contains this signature: theFunction(object, path, value)
-
If the attacker can control the value of “path”, they can set this value to __proto__.myValue. myValue is then assigned to the prototype of the class of the object.
-
Types of attacks
-
There are a few methods by which Prototype Pollution can be manipulated:
-
-
-
- Type
- Origin
- Short description
-
-
-
- Denial of service (DoS)
- Client
- This is the most likely attack. DoS occurs when Object holds generic functions that are implicitly called for various operations (for example, toString and valueOf). The attacker pollutes Object.prototype.someattr and alters its state to an unexpected value such as Int or Object. In this case, the code fails and is likely to cause a denial of service. For example: if an attacker pollutes Object.prototype.toString by defining it as an integer, if the codebase at any point was reliant on someobject.toString() it would fail.
-
-
- Remote Code Execution
- Client
- Remote code execution is generally only possible in cases where the codebase evaluates a specific attribute of an object, and then executes that evaluation.For example: eval(someobject.someattr). In this case, if the attacker pollutes Object.prototype.someattr they are likely to be able to leverage this in order to execute code.
-
-
- Property Injection
- Client
- The attacker pollutes properties that the codebase relies on for their informative value, including security properties such as cookies or tokens. For example: if a codebase checks privileges for someuser.isAdmin, then when the attacker pollutes Object.prototype.isAdmin and sets it to equal true, they can then achieve admin privileges.
-
-
-
Affected environments
-
The following environments are susceptible to a Prototype Pollution attack:
-
- Application server
-
- Web server
-
- Web browser
-
-
-
How to prevent
-
- Freeze the prototype— use Object.freeze (Object.prototype).
-
- Require schema validation of JSON input.
-
- Avoid using unsafe recursive merge functions.
-
- Consider using objects without prototypes (for example, Object.create(null)), breaking the prototype chain and preventing pollution.
-
- As a best practice use Map instead of Object.
-
-
-
-
Arteau, Oliver. “JavaScript prototype pollution attack in NodeJS application.” GitHub, 26 May 2018
-
-
Upgrade redoc to version 2.4.0 or higher.
-
References
-
-
-
-
-
-
-
LGPL-3.0 license
@@ -656,7 +490,7 @@
@@ -682,11 +516,11 @@
@@ -780,7 +614,7 @@
@@ -806,9 +640,9 @@
-
-
Arbitrary Code Injection
-
-
-
- low severity
-
-
-
-
-
-
-
-
-
-
Detailed paths
-
-
-
-
-
-
-
-
Overview
-
prismjs is a lightweight, robust, elegant syntax highlighting library.
-
Affected versions of this package are vulnerable to Arbitrary Code Injection via the document.currentScript lookup process. An attacker can manipulate the web page content and execute unintended actions by injecting HTML elements that overshadow legitimate DOM elements.
-
Note:
-
This is only exploitable if the application accepts untrusted input containing HTML but not direct JavaScript.
-
-
Upgrade prismjs to version 1.30.0 or higher.
-
References
-
-
-
-
-
-
-
-
-
Cross-site Scripting (XSS)
-
-
-
- low severity
-
-
-
-
-
-
-
-
-
-
Detailed paths
-
-
-
-
-
-
-
-
Overview
-
dompurify is a DOM-only XSS sanitizer for HTML, MathML and SVG.
-
Affected versions of this package are vulnerable to Cross-site Scripting (XSS) due to incorrect handling of template literals in regular expressions. An attacker can manipulate the output of the script by injecting malicious payloads that bypass the dompurify sanitization.
-
PoC
-
DOMPurify.sanitize(
- `<math><foo-test><mi><li><table><foo-test><li></li></foo-test><a>
- <style>
- <! \${
- </style>
- }
- <foo-b id="><img src onerror='alert(1)'>">hmm...</foo-b>
- </a></table></li></mi></foo-test></math>
- `,
- {
- SAFE_FOR_TEMPLATES: true,
- CUSTOM_ELEMENT_HANDLING: {
- tagNameCheck: /^foo-/,
- },
- }
- );
-
-
Details
-
A cross-site scripting attack occurs when the attacker tricks a legitimate web-based application or site to accept a request as originating from a trusted source.
-
This is done by escaping the context of the web application; the web application then delivers that data to its users along with other trusted dynamic content, without validating it. The browser unknowingly executes malicious script on the client side (through client-side languages; usually JavaScript or HTML) in order to perform actions that are otherwise typically blocked by the browser’s Same Origin Policy.
-
Injecting malicious code is the most prevalent manner by which XSS is exploited; for this reason, escaping characters in order to prevent this manipulation is the top method for securing code against this vulnerability.
-
Escaping means that the application is coded to mark key characters, and particularly key characters included in user input, to prevent those characters from being interpreted in a dangerous context. For example, in HTML, < can be coded as < and > can be coded as > in order to be interpreted and displayed as themselves in text, while within the code itself, they are used for HTML tags. If malicious content is injected into an application that escapes special characters and that malicious content uses < and > as HTML tags, those characters are nonetheless not interpreted as HTML tags by the browser if they’ve been correctly escaped in the application code and in this way the attempted attack is diverted.
-
The most prominent use of XSS is to steal cookies (source: OWASP HttpOnly) and hijack user sessions, but XSS exploits have been used to expose sensitive information, enable access to privileged services and functionality and deliver malware.
-
Types of attacks
-
There are a few methods by which XSS can be manipulated:
-
-
-
- Type
- Origin
- Description
-
-
-
- Stored
- Server
- The malicious code is inserted in the application (usually as a link) by the attacker. The code is activated every time a user clicks the link.
-
-
- Reflected
- Server
- The attacker delivers a malicious link externally from the vulnerable web site application to a user. When clicked, malicious code is sent to the vulnerable web site, which reflects the attack back to the user’s browser.
-
-
- DOM-based
- Client
- The attacker forces the user’s browser to render a malicious page. The data in the page itself delivers the cross-site scripting data.
-
-
- Mutated
-
- The attacker injects code that appears safe, but is then rewritten and modified by the browser, while parsing the markup. An example is rebalancing unclosed quotation marks or even adding quotation marks to unquoted parameters.
-
-
-
Affected environments
-
The following environments are susceptible to an XSS attack:
-
- Web servers
- Application servers
- Web application environments
-
-
How to prevent
-
This section describes the top best practices designed to specifically protect your code:
-
- Sanitize data input in an HTTP request before reflecting it back, ensuring all data is validated, filtered or escaped before echoing anything back to the user, such as the values of query parameters during searches.
- Convert special characters such as ?, &, /, <, > and spaces to their respective HTML or URL encoded equivalents.
- Give users the option to disable client-side scripts.
- Redirect invalid requests.
- Detect simultaneous logins, including those from two separate IP addresses, and invalidate those sessions.
- Use and enforce a Content Security Policy (source: Wikipedia) to disable any features that might be manipulated for an XSS attack.
- Read the documentation for any of the libraries referenced in your code to understand which elements allow for embedded HTML.
-
-
-
Upgrade dompurify to version 3.2.4 or higher.
-
References
-
-
-
-
-
-
-
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 1dbfa49be8..b67a18ff82 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
@@ -7,7 +7,7 @@
Snyk test report
-
+
@@ -456,7 +456,7 @@
Scanned the following paths:
@@ -469,8 +469,8 @@
@@ -552,319 +552,6 @@
More about this vulnerability
-
-
-
Allocation of Resources Without Limits or Throttling
-
-
-
- high severity
-
-
-
-
-
-
-
-
-
-
Detailed paths
-
-
-
-
-
-
-
-
Overview
-
Affected versions of this package are vulnerable to Allocation of Resources Without Limits or Throttling due to improper parsing of malformed tokens which can lead to memory consumption.
-
-
Upgrade golang.org/x/oauth2/jws to version 0.27.0 or higher.
-
References
-
-
-
-
-
-
-
-
-
Server-side Request Forgery (SSRF)
-
-
-
- high severity
-
-
-
-
-
-
-
-
-
-
Detailed paths
-
-
-
-
-
-
-
-
Overview
-
golang.org/x/net/http/httpproxy is a package for HTTP proxy determination based on environment variables, as provided by net/http's ProxyFromEnvironment function
-
Affected versions of this package are vulnerable to Server-side Request Forgery (SSRF) in proxy.go, because hostname matching against proxy patterns may treat an IPv6 zone ID as a hostname component. An environment variable value like *.example.com could be matched to a request intended for [::1%25.example.com]:80.
-
-
Upgrade golang.org/x/net/http/httpproxy to version 0.36.0 or higher.
-
References
-
-
-
-
-
-
-
-
-
Denial of Service (DoS)
-
-
-
- high severity
-
-
-
-
-
-
-
-
-
-
Detailed paths
-
-
-
-
-
-
-
-
Overview
-
golang.org/x/net/html is a package that implements an HTML5-compliant tokenizer and parser.
-
Affected versions of this package are vulnerable to Denial of Service (DoS) through the functions parseDoctype, htmlIntegrationPoint, inBodyIM and inTableIM due to inefficient usage of the method strings.ToLower combining with the == operator to convert strings to lowercase and then comparing them.
-
An attacker can cause the application to slow down significantly by crafting inputs that are processed non-linearly.
-
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
-
-
-
-
Upgrade golang.org/x/net/html to version 0.33.0 or higher.
-
References
-
-
-
-
-
-
-
-
-
Allocation of Resources Without Limits or Throttling
-
-
-
- high severity
-
-
-
-
-
-
-
-
-
-
Detailed paths
-
-
-
-
-
-
-
-
Overview
-
golang.org/x/crypto/ssh is a SSH client and server
-
Affected versions of this package are vulnerable to Allocation of Resources Without Limits or Throttling in handshakeTransport in handshake.go. An internal queue gets populated with received packets during the key exchange process, while waiting for the client to send a SSH_MSG_KEXINIT. An attacker can cause the server to become unresponsive to new connections by delaying or withholding this message, or by causing the queue to consume all available memory.
-
-
Upgrade golang.org/x/crypto/ssh to version 0.35.0 or higher.
-
References
-
-
-
-
-
-
-
-
-
Allocation of Resources Without Limits or Throttling
-
-
-
- medium severity
-
-
-
-
-
-
-
-
-
-
Detailed paths
-
-
-
-
-
-
-
-
Overview
-
Affected versions of this package are vulnerable to Allocation of Resources Without Limits or Throttling due to the use of strings.Split to split JWT tokens. An attacker can cause memory exhaustion and service disruption by sending numerous malformed tokens with a large number of . characters.
-
Workaround
-
This vulnerability can be mitigated by pre-validating that payloads passed to Go JOSE do not contain an excessive number of . characters.
-
-
Upgrade github.com/go-jose/go-jose/v4 to version 4.0.5 or higher.
-
References
-
-
-
-
-
-
CVE-2024-6119
@@ -2531,7 +2139,7 @@
cannot easily be ruled out.
The FIPS modules in 3.3, 3.2, 3.1 and 3.0 are not affected by this issue.
-
Upgrade Alpine:3.20 openssl to version 3.3.2-r3 or higher.
+
Upgrade Alpine:3.20 openssl to version 3.3.2-r1 or higher.
References
-
-
CVE-2024-13176
-
-
-
- low severity
-
-
-
-
-
-
-
-
-
-
Detailed paths
-
-
-
-
-
-
-
-
NVD Description
-
Note: Versions mentioned in the description apply only to the upstream openssl package and not the openssl package as distributed by Alpine.
- See How to fix? for Alpine:3.20 relevant fixed versions and status.
-
Issue summary: A timing side-channel which could potentially allow recovering
- the private key exists in the ECDSA signature computation.
-
Impact summary: A timing side-channel in ECDSA signature computations
- could allow recovering the private key by an attacker. However, measuring
- the timing would require either local access to the signing application or
- a very fast network connection with low latency.
-
There is a timing signal of around 300 nanoseconds when the top word of
- the inverted ECDSA nonce value is zero. This can happen with significant
- probability only for some of the supported elliptic curves. In particular
- the NIST P-521 curve is affected. To be able to measure this leak, the attacker
- process must either be located in the same physical computer or must
- have a very fast network connection with low latency. For that reason
- the severity of this vulnerability is Low.
-
-
Upgrade Alpine:3.20 openssl to version 3.3.2-r2 or higher.
-
References
-
-
-
-
-
-
-
-
-
CVE-2024-12797
-
-
-
- low severity
-
-
-
-
-
-
-
-
-
-
Detailed paths
-
-
-
-
-
-
-
-
NVD Description
-
Note: Versions mentioned in the description apply only to the upstream openssl package and not the openssl package as distributed by Alpine.
- See How to fix? for Alpine:3.20 relevant fixed versions and status.
-
Issue summary: Clients using RFC7250 Raw Public Keys (RPKs) to authenticate a
- server may fail to notice that the server was not authenticated, because
- handshakes don't abort as expected when the SSL_VERIFY_PEER verification mode
- is set.
-
Impact summary: TLS and DTLS connections using raw public keys may be
- vulnerable to man-in-middle attacks when server authentication failure is not
- detected by clients.
-
RPKs are disabled by default in both TLS clients and TLS servers. The issue
- only arises when TLS clients explicitly enable RPK use by the server, and the
- server, likewise, enables sending of an RPK instead of an X.509 certificate
- chain. The affected clients are those that then rely on the handshake to
- fail when the server's RPK fails to match one of the expected public keys,
- by setting the verification mode to SSL_VERIFY_PEER.
-
Clients that enable server-side raw public keys can still find out that raw
- public key verification failed by calling SSL_get_verify_result(), and those
- that do, and take appropriate action, are not affected. This issue was
- introduced in the initial implementation of RPK support in OpenSSL 3.2.
-
The FIPS modules in 3.4, 3.3, 3.2, 3.1 and 3.0 are not affected by this issue.
-
-
Upgrade Alpine:3.20 openssl to version 3.3.3-r0 or higher.
-
References
-
-
-
-
-
-
-
-
-
CVE-2025-26519
-
-
-
- low severity
-
-
-
-
-
-
-
-
-
-
Detailed paths
-
-
-
-
-
-
-
-
NVD Description
-
Note: Versions mentioned in the description apply only to the upstream musl package and not the musl package as distributed by Alpine.
- See How to fix? for Alpine:3.20 relevant fixed versions and status.
-
musl libc 0.9.13 through 1.2.5 before 1.2.6 has an out-of-bounds write vulnerability when an attacker can trigger iconv conversion of untrusted EUC-KR text to UTF-8.
-
-
Upgrade Alpine:3.20 musl to version 1.2.5-r1 or higher.
-
References
-
-
-
-
-
-
-
diff --git a/docs/snyk/v2.13.5/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
similarity index 67%
rename from docs/snyk/v2.13.5/public.ecr.aws_docker_library_haproxy_2.6.17-alpine.html
rename to docs/snyk/master/public.ecr.aws_docker_library_haproxy_2.6.17-alpine.html
index a6c4f64711..5dc1585aad 100644
--- a/docs/snyk/v2.13.5/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
@@ -7,7 +7,7 @@
Snyk test report
-
+
@@ -456,7 +456,7 @@
Scanned the following path:
@@ -466,8 +466,8 @@
@@ -1508,7 +1508,7 @@
cannot easily be ruled out.
The FIPS modules in 3.3, 3.2, 3.1 and 3.0 are not affected by this issue.
- Upgrade Alpine:3.20 openssl to version 3.3.2-r3 or higher.
+ Upgrade Alpine:3.20 openssl to version 3.3.2-r1 or higher.
References
https://github.com/openssl/openssl/commit/72ae83ad214d2eef262461365a1975707f862712
@@ -1531,611 +1531,6 @@
-
-
CVE-2024-13176
-
-
-
- low severity
-
-
-
-
-
-
-
-
-
-
Detailed paths
-
-
-
-
-
-
-
-
NVD Description
-
Note: Versions mentioned in the description apply only to the upstream openssl package and not the openssl package as distributed by Alpine.
- See How to fix? for Alpine:3.20 relevant fixed versions and status.
-
Issue summary: A timing side-channel which could potentially allow recovering
- the private key exists in the ECDSA signature computation.
-
Impact summary: A timing side-channel in ECDSA signature computations
- could allow recovering the private key by an attacker. However, measuring
- the timing would require either local access to the signing application or
- a very fast network connection with low latency.
-
There is a timing signal of around 300 nanoseconds when the top word of
- the inverted ECDSA nonce value is zero. This can happen with significant
- probability only for some of the supported elliptic curves. In particular
- the NIST P-521 curve is affected. To be able to measure this leak, the attacker
- process must either be located in the same physical computer or must
- have a very fast network connection with low latency. For that reason
- the severity of this vulnerability is Low.
-
-
Upgrade Alpine:3.20 openssl to version 3.3.2-r2 or higher.
-
References
-
-
-
-
-
-
-
-
-
CVE-2024-12797
-
-
-
- low severity
-
-
-
-
-
-
-
-
-
-
Detailed paths
-
-
-
-
-
-
-
-
NVD Description
-
Note: Versions mentioned in the description apply only to the upstream openssl package and not the openssl package as distributed by Alpine.
- See How to fix? for Alpine:3.20 relevant fixed versions and status.
-
Issue summary: Clients using RFC7250 Raw Public Keys (RPKs) to authenticate a
- server may fail to notice that the server was not authenticated, because
- handshakes don't abort as expected when the SSL_VERIFY_PEER verification mode
- is set.
-
Impact summary: TLS and DTLS connections using raw public keys may be
- vulnerable to man-in-middle attacks when server authentication failure is not
- detected by clients.
-
RPKs are disabled by default in both TLS clients and TLS servers. The issue
- only arises when TLS clients explicitly enable RPK use by the server, and the
- server, likewise, enables sending of an RPK instead of an X.509 certificate
- chain. The affected clients are those that then rely on the handshake to
- fail when the server's RPK fails to match one of the expected public keys,
- by setting the verification mode to SSL_VERIFY_PEER.
-
Clients that enable server-side raw public keys can still find out that raw
- public key verification failed by calling SSL_get_verify_result(), and those
- that do, and take appropriate action, are not affected. This issue was
- introduced in the initial implementation of RPK support in OpenSSL 3.2.
-
The FIPS modules in 3.4, 3.3, 3.2, 3.1 and 3.0 are not affected by this issue.
-
-
Upgrade Alpine:3.20 openssl to version 3.3.3-r0 or higher.
-
References
-
-
-
-
-
-
-
-
-
CVE-2025-26519
-
-
-
- low severity
-
-
-
-
-
-
-
-
-
-
Detailed paths
-
-
-
-
-
-
-
-
NVD Description
-
Note: Versions mentioned in the description apply only to the upstream musl package and not the musl package as distributed by Alpine.
- See How to fix? for Alpine:3.20 relevant fixed versions and status.
-
musl libc 0.9.13 through 1.2.5 before 1.2.6 has an out-of-bounds write vulnerability when an attacker can trigger iconv conversion of untrusted EUC-KR text to UTF-8.
-
-
Upgrade Alpine:3.20 musl to version 1.2.5-r1 or higher.
-
References
-
-
-
-
-
-
-
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
new file mode 100644
index 0000000000..43f65cad79
--- /dev/null
+++ b/docs/snyk/master/public.ecr.aws_docker_library_redis_7.0.15-alpine.html
@@ -0,0 +1,670 @@
+
+
+
+
+
+
+
+
+ Snyk test report
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
CVE-2024-9143
+
+
+
+ low severity
+
+
+
+
+
+
+
+
+
+
Detailed paths
+
+
+
+
+
+
+
+
NVD Description
+
Note: Versions mentioned in the description apply only to the upstream openssl package and not the openssl package as distributed by Alpine.
+ See How to fix? for Alpine:3.20 relevant fixed versions and status.
+
Issue summary: Use of the low-level GF(2^m) elliptic curve APIs with untrusted
+ explicit values for the field polynomial can lead to out-of-bounds memory reads
+ or writes.
+
Impact summary: Out of bound memory writes can lead to an application crash or
+ even a possibility of a remote code execution, however, in all the protocols
+ involving Elliptic Curve Cryptography that we're aware of, either only "named
+ curves" are supported, or, if explicit curve parameters are supported, they
+ specify an X9.62 encoding of binary (GF(2^m)) curves that can't represent
+ problematic input values. Thus the likelihood of existence of a vulnerable
+ application is low.
+
In particular, the X9.62 encoding is used for ECC keys in X.509 certificates,
+ so problematic inputs cannot occur in the context of processing X.509
+ certificates. Any problematic use-cases would have to be using an "exotic"
+ curve encoding.
+
The affected APIs include: EC_GROUP_new_curve_GF2m(), EC_GROUP_new_from_params(),
+ and various supporting BN_GF2m_*() functions.
+
Applications working with "exotic" explicit binary (GF(2^m)) curve parameters,
+ that make it possible to represent invalid field polynomials with a zero
+ constant term, via the above or similar APIs, may terminate abruptly as a
+ result of reading or writing outside of array bounds. Remote code execution
+ cannot easily be ruled out.
+
The FIPS modules in 3.3, 3.2, 3.1 and 3.0 are not affected by this issue.
+
+
Upgrade Alpine:3.20 openssl to version 3.3.2-r1 or higher.
+
References
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/docs/snyk/master/quay.io_argoproj_argocd_latest.html b/docs/snyk/master/quay.io_argoproj_argocd_latest.html
index b6af39b86c..7617106e2e 100644
--- a/docs/snyk/master/quay.io_argoproj_argocd_latest.html
+++ b/docs/snyk/master/quay.io_argoproj_argocd_latest.html
@@ -7,7 +7,7 @@
Snyk test report
-
+
@@ -456,13 +456,13 @@
Scanned the following paths:
quay.io/argoproj/argocd:latest/argoproj/argocd/Dockerfile (deb)
- quay.io/argoproj/argocd:latest/argoproj/argo-cd/v3//usr/local/bin/argocd (gomodules)
+ quay.io/argoproj/argocd:latest/argoproj/argo-cd/v2//usr/local/bin/argocd (gomodules)
quay.io/argoproj/argocd:latest//usr/local/bin/kustomize (gomodules)
quay.io/argoproj/argocd:latest/helm/v3//usr/local/bin/helm (gomodules)
quay.io/argoproj/argocd:latest/git-lfs/git-lfs//usr/bin/git-lfs (gomodules)
@@ -470,9 +470,9 @@
@@ -480,111 +480,6 @@
-
-
CVE-2024-56433
-
-
-
- medium severity
-
-
-
-
-
-
-
-
-
-
Detailed paths
-
-
-
-
-
-
-
-
NVD Description
-
Note: Versions mentioned in the description apply only to the upstream shadow package and not the shadow package as distributed by Ubuntu.
- See How to fix? for Ubuntu:24.04 relevant fixed versions and status.
-
shadow-utils (aka shadow) 4.4 through 4.17.0 establishes a default /etc/subuid behavior (e.g., uid 100000 through 165535 for the first user account) that can realistically conflict with the uids of users defined on locally administered networks, potentially leading to account takeover, e.g., by leveraging newuidmap for access to an NFS home directory (or same-host resources in the case of remote logins by these local network users). NOTE: it may also be argued that system administrators should not have assigned uids, within local networks, that are within the range that can occur in /etc/subuid.
-
-
There is no fixed version for Ubuntu:24.04 shadow.
-
References
-
-
-
-
-
-
-
Insecure Storage of Sensitive Information
@@ -645,7 +540,7 @@
Introduced through :
docker-image|quay.io/argoproj/argocd@latest
›
- util-linux@2.39.3-9ubuntu6.2
+ util-linux@2.39.3-9ubuntu6.1
›
pam/libpam0g@1.5.3-5ubuntu5.1
@@ -814,7 +709,6 @@
https://bugzilla.redhat.com/show_bug.cgi?id=2319212
https://access.redhat.com/errata/RHSA-2024:9941
https://access.redhat.com/errata/RHSA-2024:10379
- https://access.redhat.com/errata/RHSA-2024:11250
@@ -884,7 +778,7 @@
Introduced through :
docker-image|quay.io/argoproj/argocd@latest
›
- util-linux@2.39.3-9ubuntu6.2
+ util-linux@2.39.3-9ubuntu6.1
›
pam/libpam0g@1.5.3-5ubuntu5.1
@@ -1051,12 +945,6 @@
http://people.ubuntu.com/~ubuntu-security/cve/CVE-2024-10963
https://access.redhat.com/security/cve/CVE-2024-10963
https://bugzilla.redhat.com/show_bug.cgi?id=2324291
- https://access.redhat.com/errata/RHSA-2024:10232
- https://access.redhat.com/errata/RHSA-2024:10244
- https://access.redhat.com/errata/RHSA-2024:10379
- https://access.redhat.com/errata/RHSA-2024:10518
- https://access.redhat.com/errata/RHSA-2024:10528
- https://access.redhat.com/errata/RHSA-2024:10852
@@ -1065,6 +953,214 @@
More about this vulnerability
+
+
+
CVE-2024-26462
+
+
+
+ medium severity
+
+
+
+
+
+
+
+
+
+
Detailed paths
+
+
+
+
+
+
+
+
NVD Description
+
Note: Versions mentioned in the description apply only to the upstream krb5 package and not the krb5 package as distributed by Ubuntu.
+ See How to fix? for Ubuntu:24.04 relevant fixed versions and status.
+
Kerberos 5 (aka krb5) 1.21.2 contains a memory leak vulnerability in /krb5/src/kdc/ndr.c.
+
+
There is no fixed version for Ubuntu:24.04 krb5.
+
References
+
+
+
+
+
+
LGPL-3.0 license
@@ -1078,7 +1174,7 @@
@@ -1104,7 +1200,7 @@
@@ -1198,7 +1294,7 @@
@@ -1224,7 +1320,7 @@
-
-
-
Generation of Error Message Containing Sensitive Information
-
-
-
- medium severity
-
-
-
-
-
-
-
-
-
-
Detailed paths
-
-
-
-
-
-
-
-
Overview
-
Affected versions of this package are vulnerable to Generation of Error Message Containing Sensitive Information when syncing invalid Kubernetes Secret resources. An attacker with write access to the repository can expose secret values by committing an invalid Secret to repository and triggering a Sync, which then become visible to any user with read access to Argo CD.
-
-
A fix was pushed into the master branch but not yet published.
-
References
-
-
-
-
-
-
-
-
-
Generation of Error Message Containing Sensitive Information
-
-
-
- medium severity
-
-
-
-
-
-
-
-
-
-
Detailed paths
-
-
-
-
-
-
-
-
Overview
-
Affected versions of this package are vulnerable to Generation of Error Message Containing Sensitive Information when syncing invalid Kubernetes Secret resources. An attacker with write access to the repository can expose secret values by committing an invalid Secret to repository and triggering a Sync, which then become visible to any user with read access to Argo CD.
-
-
A fix was pushed into the master branch but not yet published.
-
References
-
-
-
-
-
-
-
-
-
Improper Encoding or Escaping of Output
-
-
-
- medium severity
-
-
-
-
-
-
-
-
-
-
Detailed paths
-
-
-
-
-
-
-
-
NVD Description
-
Note: Versions mentioned in the description apply only to the upstream git package and not the git package as distributed by Ubuntu.
- See How to fix? for Ubuntu:24.04 relevant fixed versions and status.
-
Git is a source code management tool. When cloning from a server (or fetching, or pushing), informational or error messages are transported from the remote Git process to the client via the so-called "sideband channel". These messages will be prefixed with "remote:" and printed directly to the standard error output. Typically, this standard error output is connected to a terminal that understands ANSI escape sequences, which Git did not protect against. Most modern terminals support control sequences that can be used by a malicious actor to hide and misrepresent information, or to mislead the user into executing untrusted scripts. As requested on the git-security mailing list, the patches are under discussion on the public mailing list. Users are advised to update as soon as possible. Users unable to upgrade should avoid recursive clones unless they are from trusted sources.
-
-
There is no fixed version for Ubuntu:24.04 git.
-
References
-
-
-
-
-
-
Release of Invalid Pointer or Reference
@@ -1887,7 +1752,7 @@
Introduced through:
- docker-image|quay.io/argoproj/argocd@latest and openssl/libssl3t64@3.0.13-0ubuntu3.5
+ docker-image|quay.io/argoproj/argocd@latest and openssl/libssl3t64@3.0.13-0ubuntu3.4
@@ -1902,7 +1767,7 @@
Introduced through :
docker-image|quay.io/argoproj/argocd@latest
›
- openssl/libssl3t64@3.0.13-0ubuntu3.5
+ openssl/libssl3t64@3.0.13-0ubuntu3.4
@@ -1913,7 +1778,7 @@
›
coreutils@9.4-3ubuntu6
›
- openssl/libssl3t64@3.0.13-0ubuntu3.5
+ openssl/libssl3t64@3.0.13-0ubuntu3.4
@@ -1924,7 +1789,7 @@
›
cyrus-sasl2/libsasl2-modules@2.1.28+dfsg1-5ubuntu3.1
›
- openssl/libssl3t64@3.0.13-0ubuntu3.5
+ openssl/libssl3t64@3.0.13-0ubuntu3.4
@@ -1935,7 +1800,7 @@
›
libfido2/libfido2-1@1.14.0-1build3
›
- openssl/libssl3t64@3.0.13-0ubuntu3.5
+ openssl/libssl3t64@3.0.13-0ubuntu3.4
@@ -1944,9 +1809,9 @@
Introduced through :
docker-image|quay.io/argoproj/argocd@latest
›
- openssh/openssh-client@1:9.6p1-3ubuntu13.8
+ openssh/openssh-client@1:9.6p1-3ubuntu13.5
›
- openssl/libssl3t64@3.0.13-0ubuntu3.5
+ openssl/libssl3t64@3.0.13-0ubuntu3.4
@@ -1957,9 +1822,9 @@
›
ca-certificates@20240203
›
- openssl@3.0.13-0ubuntu3.5
+ openssl@3.0.13-0ubuntu3.4
›
- openssl/libssl3t64@3.0.13-0ubuntu3.5
+ openssl/libssl3t64@3.0.13-0ubuntu3.4
@@ -1968,13 +1833,13 @@
Introduced through :
docker-image|quay.io/argoproj/argocd@latest
›
- git@1:2.43.0-1ubuntu7.2
+ git@1:2.43.0-1ubuntu7.1
›
- curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.6
+ curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.5
›
libssh/libssh-4@0.10.6-2build2
›
- openssl/libssl3t64@3.0.13-0ubuntu3.5
+ openssl/libssl3t64@3.0.13-0ubuntu3.4
@@ -1983,15 +1848,15 @@
Introduced through :
docker-image|quay.io/argoproj/argocd@latest
›
- git@1:2.43.0-1ubuntu7.2
+ git@1:2.43.0-1ubuntu7.1
›
- curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.6
+ curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.5
›
- krb5/libgssapi-krb5-2@1.20.1-6ubuntu2.5
+ krb5/libgssapi-krb5-2@1.20.1-6ubuntu2.2
›
- krb5/libkrb5-3@1.20.1-6ubuntu2.5
+ krb5/libkrb5-3@1.20.1-6ubuntu2.2
›
- openssl/libssl3t64@3.0.13-0ubuntu3.5
+ openssl/libssl3t64@3.0.13-0ubuntu3.4
@@ -2000,15 +1865,15 @@
Introduced through :
docker-image|quay.io/argoproj/argocd@latest
›
- git@1:2.43.0-1ubuntu7.2
+ git@1:2.43.0-1ubuntu7.1
›
- curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.6
+ curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.5
›
- openldap/libldap2@2.6.7+dfsg-1~exp1ubuntu8.2
+ openldap/libldap2@2.6.7+dfsg-1~exp1ubuntu8.1
›
cyrus-sasl2/libsasl2-2@2.1.28+dfsg1-5ubuntu3.1
›
- openssl/libssl3t64@3.0.13-0ubuntu3.5
+ openssl/libssl3t64@3.0.13-0ubuntu3.4
@@ -2017,7 +1882,7 @@
Introduced through :
docker-image|quay.io/argoproj/argocd@latest
›
- openssl@3.0.13-0ubuntu3.5
+ openssl@3.0.13-0ubuntu3.4
@@ -2028,7 +1893,7 @@
›
ca-certificates@20240203
›
- openssl@3.0.13-0ubuntu3.5
+ openssl@3.0.13-0ubuntu3.4
@@ -2189,7 +2054,7 @@
›
pam/libpam-modules@1.5.3-5ubuntu5.1
›
- systemd/libsystemd0@255.4-1ubuntu8.5
+ systemd/libsystemd0@255.4-1ubuntu8.4
›
libgcrypt20@1.10.3-2build1
@@ -2223,6 +2088,422 @@
More about this vulnerability
+
+
+
CVE-2024-26458
+
+
+
+ low severity
+
+
+
+
+
+
+
+
+
+
Detailed paths
+
+
+
+
+
+
+
+
NVD Description
+
Note: Versions mentioned in the description apply only to the upstream krb5 package and not the krb5 package as distributed by Ubuntu.
+ See How to fix? for Ubuntu:24.04 relevant fixed versions and status.
+
Kerberos 5 (aka krb5) 1.21.2 contains a memory leak in /krb5/src/lib/rpc/pmap_rmt.c.
+
+
There is no fixed version for Ubuntu:24.04 krb5.
+
References
+
+
+
+
+
+
+
+
+
CVE-2024-26461
+
+
+
+ low severity
+
+
+
+
+
+
+
+
+
+
Detailed paths
+
+
+
+
+
+
+
+
NVD Description
+
Note: Versions mentioned in the description apply only to the upstream krb5 package and not the krb5 package as distributed by Ubuntu.
+ See How to fix? for Ubuntu:24.04 relevant fixed versions and status.
+
Kerberos 5 (aka krb5) 1.21.2 contains a memory leak vulnerability in /krb5/src/lib/gssapi/krb5/k5sealv3.c.
+
+
There is no fixed version for Ubuntu:24.04 krb5.
+
References
+
+
+
+
+
+
Out-of-bounds Write
@@ -2395,7 +2676,7 @@
Introduced through:
- docker-image|quay.io/argoproj/argocd@latest and glibc/libc-bin@2.39-0ubuntu8.4
+ docker-image|quay.io/argoproj/argocd@latest and glibc/libc-bin@2.39-0ubuntu8.3
@@ -2410,7 +2691,7 @@
Introduced through :
docker-image|quay.io/argoproj/argocd@latest
›
- glibc/libc-bin@2.39-0ubuntu8.4
+ glibc/libc-bin@2.39-0ubuntu8.3
@@ -2419,7 +2700,7 @@
Introduced through :
docker-image|quay.io/argoproj/argocd@latest
›
- glibc/libc6@2.39-0ubuntu8.4
+ glibc/libc6@2.39-0ubuntu8.3
@@ -2452,7 +2733,7 @@
-
CVE-2025-0167
+
Improper Input Validation
@@ -2471,13 +2752,13 @@
Vulnerable module:
- curl/libcurl3t64-gnutls
+ git/git-man
Introduced through:
- docker-image|quay.io/argoproj/argocd@latest, git@1:2.43.0-1ubuntu7.2 and others
+ docker-image|quay.io/argoproj/argocd@latest, git@1:2.43.0-1ubuntu7.1 and others
@@ -2491,9 +2772,29 @@
Introduced through :
docker-image|quay.io/argoproj/argocd@latest
›
- git@1:2.43.0-1ubuntu7.2
+ git@1:2.43.0-1ubuntu7.1
›
- curl/libcurl3t64-gnutls@8.5.0-2ubuntu10.6
+ git/git-man@1:2.43.0-1ubuntu7.1
+
+
+
+
+
+ Introduced through :
+ docker-image|quay.io/argoproj/argocd@latest
+ ›
+ git@1:2.43.0-1ubuntu7.1
+
+
+
+
+
+ Introduced through :
+ docker-image|quay.io/argoproj/argocd@latest
+ ›
+ git-lfs@3.4.1-1ubuntu0.2
+ ›
+ git@1:2.43.0-1ubuntu7.1
@@ -2505,28 +2806,22 @@
NVD Description
- Note: Versions mentioned in the description apply only to the upstream curl package and not the curl package as distributed by Ubuntu.
+
Note: Versions mentioned in the description apply only to the upstream git package and not the git package as distributed by Ubuntu.
See How to fix? for Ubuntu:24.04 relevant fixed versions and status.
- When asked to 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 a default entry that
- omits both login and password. A rare circumstance.
+ GIT version 2.15.1 and earlier contains a Input Validation Error vulnerability in Client that can result in problems including messing up terminal configuration to RCE. This attack appear to be exploitable via The user must interact with a malicious git server, (or have their traffic modified in a MITM attack).
- There is no fixed version for Ubuntu:24.04 curl.
+ There is no fixed version for Ubuntu:24.04 git.
References
diff --git a/docs/snyk/master/redis_7.2.7-alpine.html b/docs/snyk/master/redis_7.0.15-alpine.html
similarity index 51%
rename from docs/snyk/master/redis_7.2.7-alpine.html
rename to docs/snyk/master/redis_7.0.15-alpine.html
index ab05e38d5f..08afe3592a 100644
--- a/docs/snyk/master/redis_7.2.7-alpine.html
+++ b/docs/snyk/master/redis_7.0.15-alpine.html
@@ -7,7 +7,7 @@
Snyk test report
-
+
@@ -456,27 +456,213 @@
Scanned the following paths:
- redis:7.2.7-alpine (apk)
- redis:7.2.7-alpine/tianon/gosu//usr/local/bin/gosu (gomodules)
+ redis:7.0.15-alpine (apk)
+ redis:7.0.15-alpine/tianon/gosu//usr/local/bin/gosu (gomodules)
- No known vulnerabilities detected.
+
+
+
CVE-2024-9143
+
+
+
+ low severity
+
+
+
+
+
+
+
+
+
+
Detailed paths
+
+
+
+
+
+
+
+
NVD Description
+
Note: Versions mentioned in the description apply only to the upstream openssl package and not the openssl package as distributed by Alpine.
+ See How to fix? for Alpine:3.20 relevant fixed versions and status.
+
Issue summary: Use of the low-level GF(2^m) elliptic curve APIs with untrusted
+ explicit values for the field polynomial can lead to out-of-bounds memory reads
+ or writes.
+
Impact summary: Out of bound memory writes can lead to an application crash or
+ even a possibility of a remote code execution, however, in all the protocols
+ involving Elliptic Curve Cryptography that we're aware of, either only "named
+ curves" are supported, or, if explicit curve parameters are supported, they
+ specify an X9.62 encoding of binary (GF(2^m)) curves that can't represent
+ problematic input values. Thus the likelihood of existence of a vulnerable
+ application is low.
+
In particular, the X9.62 encoding is used for ECC keys in X.509 certificates,
+ so problematic inputs cannot occur in the context of processing X.509
+ certificates. Any problematic use-cases would have to be using an "exotic"
+ curve encoding.
+
The affected APIs include: EC_GROUP_new_curve_GF2m(), EC_GROUP_new_from_params(),
+ and various supporting BN_GF2m_*() functions.
+
Applications working with "exotic" explicit binary (GF(2^m)) curve parameters,
+ that make it possible to represent invalid field polynomials with a zero
+ constant term, via the above or similar APIs, may terminate abruptly as a
+ result of reading or writing outside of array bounds. Remote code execution
+ cannot easily be ruled out.
+
The FIPS modules in 3.3, 3.2, 3.1 and 3.0 are not affected by this issue.
+
+
Upgrade Alpine:3.20 openssl to version 3.3.2-r1 or higher.
+
References
+
+
+
+
+
+
+
+