| 1 | # https://github.com/actions/cache/blob/main/tips-and-workarounds.md#force-deletion-of-caches-overriding-default-cache-eviction-policy |
| 2 | |
| 3 | name: (Shared) Cleanup Stale Branch Caches |
| 4 | on: |
| 5 | schedule: |
| 6 | # Every 6 hours |
| 7 | - cron: 0 */6 * * * |
| 8 | workflow_dispatch: |
| 9 | |
| 10 | permissions: {} |
| 11 | |
| 12 | jobs: |
| 13 | cleanup: |
| 14 | runs-on: ubuntu-latest |
| 15 | permissions: |
| 16 | # `actions:write` permission is required to delete caches |
| 17 | # See also: https://docs.github.com/en/rest/actions/cache?apiVersion=2022-11-28#delete-a-github-actions-cache-for-a-repository-using-a-cache-id |
| 18 | actions: write |
| 19 | contents: read |
| 20 | steps: |
| 21 | - name: Cleanup |
| 22 | run: | |
| 23 | echo "Fetching list of cache keys" |
| 24 | cacheKeysForPR=$(gh cache list --limit 100 --json id,ref --jq '.[] | select(.ref != "refs/heads/main") | .id') |
| 25 | |
| 26 | ## Setting this to not fail the workflow while deleting cache keys. |
| 27 | set +e |
| 28 | for cacheKey in $cacheKeysForPR |
| 29 | do |
| 30 | gh cache delete $cacheKey |
| 31 | echo "Deleting $cacheKey" |
| 32 | done |
| 33 | echo "Done" |
| 34 | env: |
| 35 | GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} |
| 36 | GH_REPO: ${{ github.repository }} |