From e0e2288cd8ee6bc58f241e426a057dcf77f6be34 Mon Sep 17 00:00:00 2001 From: Ladislas de Toldi Date: Fri, 25 Oct 2024 11:22:18 +0200 Subject: [PATCH] =?UTF-8?q?=F0=9F=91=B7=20(workflows):=20Add=20workflow=20?= =?UTF-8?q?to=20cancel=20ongoing=20workflows=20on=20PR=20closed?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...ci-tools-cancel_workflows_on_pr_closed.yml | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 .github/workflows/ci-tools-cancel_workflows_on_pr_closed.yml diff --git a/.github/workflows/ci-tools-cancel_workflows_on_pr_closed.yml b/.github/workflows/ci-tools-cancel_workflows_on_pr_closed.yml new file mode 100644 index 0000000000..aa6ea3aaf9 --- /dev/null +++ b/.github/workflows/ci-tools-cancel_workflows_on_pr_closed.yml @@ -0,0 +1,45 @@ +name: Cancel Workflows on PR Close + +on: + pull_request: + types: [closed] + +jobs: + cancel-workflows: + runs-on: ubuntu-latest + permissions: + actions: write # Ensure we have permission to cancel workflows + steps: + - name: Cancel Running Workflows + uses: actions/github-script@v7 + with: + script: | + const prNumber = context.payload.pull_request.number; + const { owner, repo } = context.repo; + const currentRunId = context.runId; // Get current workflow run ID + + // Fetch all in-progress workflow runs triggered by pull requests + const runs = await github.paginate( + github.rest.actions.listWorkflowRunsForRepo, + { + owner, + repo, + event: 'pull_request', + status: 'in_progress', + } + ); + + // Cancel runs associated with the closed PR, excluding the current run + for (const run of runs) { + if ( + run.id !== currentRunId && // Exclude current run + run.pull_requests.some(pr => pr.number === prNumber) + ) { + await github.rest.actions.cancelWorkflowRun({ + owner, + repo, + run_id: run.id, + }); + console.log(`Cancelled workflow run: ${run.id}`); + } + }