diff --git a/.github/workflows/cancel-pr-workflows.yml b/.github/workflows/cancel-pr-workflows.yml new file mode 100644 index 0000000000..7120231aec --- /dev/null +++ b/.github/workflows/cancel-pr-workflows.yml @@ -0,0 +1,51 @@ +name: Cancel PR Workflows + +on: + pull_request: + types: [closed] + +jobs: + cancel: + name: Cancel In-Progress Workflows + runs-on: ubuntu-latest + steps: + - name: Cancel in-progress workflow runs + uses: actions/github-script@v7 + with: + script: | + const { owner, repo } = context.repo; + const branch = context.payload.pull_request.head.ref; + + const workflows = await github.rest.actions.listWorkflowRunsForRepo({ + owner, + repo, + branch, + status: 'in_progress', + }); + + const waitingWorkflows = await github.rest.actions.listWorkflowRunsForRepo({ + owner, + repo, + branch, + status: 'queued', + }); + + const runs = [...workflows.data.workflow_runs, ...waitingWorkflows.data.workflow_runs]; + + for (const run of runs) { + if (run.id === context.runId) { + continue; + } + try { + console.log(`Cancelling run ${run.id} (${run.name})`); + await github.rest.actions.cancelWorkflowRun({ + owner, + repo, + run_id: run.id, + }); + } catch (error) { + console.log(`Failed to cancel run ${run.id}: ${error.message}`); + } + } + + console.log(`Cancelled ${runs.length > 1 ? runs.length - 1 : 0} workflow run(s) for branch ${branch}`);