From 07f536d05ddd1d00dfc882b0c220b9042230c0c2 Mon Sep 17 00:00:00 2001
From: Oliver Luo <127242586+oliver-z-luo@users.noreply.github.com>
Date: Mon, 27 Nov 2023 05:14:15 -0800
Subject: [PATCH] Skip build and push if image already exists on ICR (#27)

* gh action trial

* adjusted if

* adjusted if

* if

* if

* added checks if image exist before build/publishing

* add conditional message

* adjusted step if

* added to github env

* gh env

* update skip build

* fails release if image exists
---
 .github/workflows/release.yml | 22 ++++++++++++++++++++++
 1 file changed, 22 insertions(+)

diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index d827540..03d4987 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -194,6 +194,27 @@ jobs:
           image_scan_result_cos_api_token: ${{ secrets.CONTAINER_IMAGE_SCAN_RESULT_COS_API_KEY }}
           fail_if_overdue: ${{ inputs.scan_fail_if_overdue }}
 
+      - name: Check image exist on ICR
+        id: check-image
+        run: |
+          IMAGE="${{ inputs.image }}:${{ github.ref_name }}"
+          if docker manifest inspect "$IMAGE" &> /dev/null ; then 
+            echo IMAGE_EXISTS=true >> "$GITHUB_ENV"
+            echo "Image found in ICR: ${IMAGE}" 
+          else 
+            echo IMAGE_EXISTS=false >> "$GITHUB_ENV"
+            echo "Image not found in ICR: ${IMAGE}" 
+          fi
+
+      - name: Fail if image already exists
+        run: |
+          if [ "$IMAGE_EXISTS" == "true" ]; then
+            echo "Image already exists. Failing the release."
+            exit 1
+          fi
+        env:
+          IMAGE_EXISTS: ${{ env.IMAGE_EXISTS }}
+
       - name: Build and push
         id: build-push
         uses: docker/build-push-action@v5
@@ -216,6 +237,7 @@ jobs:
           build-args: |-
             SN_GITHUB_NPM_TOKEN=${{ secrets.NPM_TOKEN }}
             SN_GITHUB_NPM_REGISTRY=https://npm.pkg.github.com
+        if: env.IMAGE_EXISTS == 'false'
 
       - uses: sigstore/cosign-installer@main
         if: ${{ inputs.push }}