---
# When a PR is closed (this includes merged into master) this job
# will remove any cache entries owned by that PR.

# This is based on:
# https://github.com/actions/cache/blob/main/tips-and-workarounds.md#force-deletion-of-caches-overriding-default-cache-eviction-policy

name: Cleanup cache from PR
on:
  pull_request_target:
    types:
      - closed

jobs:
  cleanup:
    runs-on: ubuntu-latest
    permissions:
      actions: write
      contents: read
    steps:
      - name: Check out code
        uses: actions/checkout@v4

      - name: Cleanup
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          gh extension install actions/gh-actions-cache

          REPO=${{ github.repository }}
          BRANCH=refs/pull/${{ github.event.pull_request.number }}/merge

          echo -n "Fetching list of cache keys:"
          KEYS=$(gh actions-cache list --limit 100 -R $REPO -B $BRANCH | cut -f 1 )
          echo $KEYS

          ## Setting this to not fail the workflow while deleting cache keys.
          set +e
          echo "Deleting caches..."
          for cacheKey in $KEYS
          do
              echo "Deleting" $cacheKey "from" $BRANCH
              gh actions-cache delete $cacheKey -R $REPO -B $BRANCH --confirm
          done
          echo "Done"
