Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

👷 (workflows): Add workflow to cancel ongoing workflows on PR closed #1529

Merged
merged 1 commit into from
Oct 25, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions .github/workflows/ci-tools-cancel_workflows_on_pr_closed.yml
Original file line number Diff line number Diff line change
@@ -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}`);
}
}
Loading