Skip to content

👷 (worflows): Improve cancel on PR closed #4

👷 (worflows): Improve cancel on PR closed

👷 (worflows): Improve cancel on PR closed #4

# Leka - iOS Monorepo
# Copyright APF France handicap
# SPDX-License-Identifier: Apache-2.0
name: Cancel Workflows on PR Close
on:
pull_request:
types: [closed]
jobs:
cancel-workflows:
runs-on: ubuntu-latest
permissions:
actions: write
pull-requests: read
steps:
- name: Cancel Running Workflows Based on Commit SHA
uses: actions/github-script@v7
with:
script: |
const prNumber = context.payload.pull_request.number;
const prHeadSha = context.payload.pull_request.head.sha;
const { owner, repo } = context.repo;
const currentRunId = context.runId;
console.log(`PR Number: ${prNumber}`);
console.log(`PR Head SHA: ${prHeadSha}`);
console.log(`Current Run ID: ${currentRunId}`);
// Fetch all in-progress and queued workflow runs
const statuses = ['in_progress', 'queued'];
let runs = [];
for (const status of statuses) {
const response = await github.rest.actions.listWorkflowRunsForRepo({
owner,
repo,
status,
});
runs = runs.concat(response.data.workflow_runs);
}
console.log(`Total in-progress or queued runs: ${runs.length}`);
runs.forEach(run => {
console.log(`Run ID: ${run.id}, Head SHA: ${run.head_sha}, Event: ${run.event}, Status: ${run.status}`);
});
// Cancel runs associated with the closed PR based on head SHA, excluding the current run
for (const run of runs) {
if (run.id !== currentRunId && run.head_sha === prHeadSha) {
await github.rest.actions.cancelWorkflowRun({
owner,
repo,
run_id: run.id,
});
console.log(`Cancelled workflow run: ${run.id}`);
}
}