1+ name : Cancel PR Workflows on Close
2+
3+ on :
4+ pull_request :
5+ types : [ closed ]
6+
7+ permissions :
8+ actions : write
9+
10+ jobs :
11+ cancel :
12+ name : Cancel In-Progress Workflows
13+ if : github.event.pull_request.merged == false
14+ runs-on : ubuntu-latest
15+ steps :
16+ - name : Cancel PR Build and System Test
17+ uses : actions/github-script@v8
18+ with :
19+ script : |
20+ const workflows = ['pr-build.yml', 'system-test.yml', 'codeql.yml', 'coverage-waiting.yml'];
21+ const headSha = context.payload.pull_request.head.sha;
22+ const prNumber = context.payload.pull_request.number;
23+
24+ for (const workflowId of workflows) {
25+ for (const status of ['in_progress', 'queued']) {
26+ const runs = await github.paginate(
27+ github.rest.actions.listWorkflowRuns,
28+ {
29+ owner: context.repo.owner,
30+ repo: context.repo.repo,
31+ workflow_id: workflowId,
32+ status,
33+ event: 'pull_request',
34+ per_page: 100,
35+ },
36+ (response) => response.data.workflow_runs
37+ );
38+
39+ for (const run of runs) {
40+ const isTargetPr = !run.pull_requests?.length || run.pull_requests.some((pr) => pr.number === prNumber);
41+ if (run.head_sha === headSha && isTargetPr) {
42+ await github.rest.actions.cancelWorkflowRun({
43+ owner: context.repo.owner,
44+ repo: context.repo.repo,
45+ run_id: run.id,
46+ });
47+ console.log(`Cancelled ${workflowId} run #${run.id} (${status})`);
48+ }
49+ }
50+ }
51+ }
0 commit comments