@@ -10,11 +10,34 @@ permissions:
1010 pull-requests : read
1111
1212jobs :
13- # When a PR is closed, delete all GitHub Actions caches associated with the PR's merge ref (refs/pull/PR_NUMBER/merge).
13+ # When a PR is closed, cancel any still-running pull_request workflow runs for
14+ # that PR and delete all GitHub Actions caches associated with the PR's merge
15+ # ref (refs/pull/PR_NUMBER/merge).
1416 cleanup :
15- name : Cleanup PR caches
17+ name : Cleanup PR actions state
1618 runs-on : ubuntu-latest
1719 steps :
20+ - name : Cancel PR workflow runs
21+ env :
22+ GH_TOKEN : ${{ github.token }}
23+ GH_REPO : ${{ github.repository }}
24+ PR_NUMBER : ${{ github.event.pull_request.number }}
25+ RUN_ID : ${{ github.run_id }}
26+ run : |
27+ set -euo pipefail
28+ run_ids=$(gh api --paginate "repos/$GH_REPO/actions/runs?event=pull_request&status=in_progress&per_page=100" --jq '.workflow_runs[] | select(.id != (env.RUN_ID | tonumber) and any(.pull_requests[]?; .number == (env.PR_NUMBER | tonumber))) | .id')
29+ queued_run_ids=$(gh api --paginate "repos/$GH_REPO/actions/runs?event=pull_request&status=queued&per_page=100" --jq '.workflow_runs[] | select(.id != (env.RUN_ID | tonumber) and any(.pull_requests[]?; .number == (env.PR_NUMBER | tonumber))) | .id')
30+ run_ids=$(printf '%s\n%s\n' "$run_ids" "$queued_run_ids" | sed '/^$/d' | sort -u)
31+ if [ -z "$run_ids" ]; then
32+ echo "No queued or in-progress pull_request runs found for PR #$PR_NUMBER"
33+ else
34+ while read -r run_id; do
35+ if ! gh api --method POST "repos/$GH_REPO/actions/runs/$run_id/cancel"; then
36+ echo "Run $run_id could not be cancelled, likely because it already finished"
37+ fi
38+ done <<< "$run_ids"
39+ fi
40+
1841 - name : Delete PR caches
1942 env :
2043 GH_TOKEN : ${{ github.token }}
0 commit comments