|
1 | 1 | /* eslint-disable camelcase */ |
2 | 2 |
|
| 3 | +// node modules |
| 4 | +import { inspect } from 'util' |
| 5 | + |
| 6 | +// packages |
3 | 7 | import core from '@actions/core' |
4 | 8 | import github from '@actions/github' |
5 | 9 |
|
6 | | -export default async function (octokit) { |
7 | | - // extract sha |
8 | | - const { sha, runId: run_id } = github.context |
9 | | - |
10 | | - // get workflow id from run id |
11 | | - const { data: { workflow_id } } = await octokit.request('GET /repos/{owner}/{repo}/actions/runs/{run_id}', { |
| 10 | +export default async function ({ octokit, workflow_id, run_id, sha }) { |
| 11 | + // get current run of this workflow |
| 12 | + const { data: { workflow_runs } } = await octokit.request('GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs', { |
12 | 13 | ...github.context.repo, |
13 | | - run_id |
| 14 | + workflow_id |
14 | 15 | }) |
15 | 16 |
|
16 | | - // get current run of this workflow |
17 | | - const { data: { workflow_runs } } = await octokit.request('GET /repos/{owner}/{repo}/actions/runs', { |
18 | | - ...github.context.repo |
19 | | - }) |
| 17 | + core.debug(`found ${workflow_runs.length} runs of workflow ${workflow_id}`) |
| 18 | + core.debug(inspect(workflow_runs)) |
20 | 19 |
|
21 | | - // find any instances of the same workflow |
| 20 | + // filter and sort |
22 | 21 | const cancellable = workflow_runs |
23 | 22 | // filter to relevant runs |
24 | | - .filter(run => ['in_progress', 'queued'].includes(run.status) && run.workflow_id === workflow_id && run.head_sha === sha) |
| 23 | + .filter(run => ['in_progress', 'queued'].includes(run.status)) |
| 24 | + // filter to only runs for the same commit |
| 25 | + .filter(run => run.head_sha === sha) |
| 26 | + // exclude this one |
| 27 | + .filter(run => run.id !== run_id) |
25 | 28 | // pick relevant properties |
26 | 29 | .map(run => ({ id: run.id, name: run.name, created_at: run.created_at })) |
27 | 30 | // sort |
28 | 31 | .sort((a, b) => new Date(b.created_at) - new Date(a.created_at)) |
29 | 32 |
|
30 | | - // remove last one |
31 | | - cancellable.pop() |
| 33 | + core.debug(`found ${cancellable.length} cancellable runs of workflow ${workflow_id}`) |
| 34 | + core.debug(inspect(cancellable)) |
| 35 | + |
| 36 | + // exclude last one (i.e. the first running instance) |
| 37 | + const prime = cancellable.pop() |
| 38 | + |
| 39 | + core.debug(`determined ${prime.id} to be the prime run of this workflow`) |
| 40 | + core.debug(inspect(prime)) |
32 | 41 |
|
33 | 42 | for (const run of cancellable) { |
34 | | - core.info(`${run.id}: ${run.name} => cancel`) |
| 43 | + core.info(`${run.id}: ${run.name} => canceling`) |
35 | 44 |
|
36 | 45 | await octokit.request('POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel', { |
37 | 46 | ...github.context.repo, |
|
0 commit comments