@@ -3,28 +3,21 @@ set -x # enable debug
33set -e # fail fast
44# simple script to cancel a github actions workflow given its name
55
6- if [ -z " $GITHUB_TOKEN " ]
7- then
8- echo " Must specify GITHUB_TOKEN"
9- exit 1
10- fi
11-
12- if [ -z " $GITHUB_REPOSITORY " ]
13- then
14- echo " Must specify GITHUB_REPOSITORY"
15- exit 1
16- fi
17-
18- if [ -z " $GITHUB_RUN_ID " ]
19- then
20- echo " Must specify GITHUB_RUN_ID"
21- exit 1
22- fi
6+ # ################### CONSTANTS AND HELPER FUNCTIONS ####################
237
248GITHUB_API=https://api.github.com
9+ ACCEPT_HEADER=" Accept: application/vnd.github.v3+json"
2510
26- auth_header=" Authorization: token ${GITHUB_TOKEN} "
27- accept_header=" Accept: application/vnd.github.v3+json"
11+ function validate_required_env_variables() {
12+ local required_env_variables=( " GITHUB_TOKEN" " GITHUB_REPOSITORY" " GITHUB_RUN_ID" )
13+
14+ for env in " ${required_env_variables[@]} " ; do
15+ if [ -z " ${! env} " ]; then
16+ echo " Must specify ${env} "
17+ exit 1
18+ fi
19+ done
20+ }
2821
2922function extractMetaInformation() {
3023 jq " { workflow_id: .workflow_id, branch: .head_branch, repo: .head_repository.full_name}"
@@ -53,19 +46,25 @@ function exportAll() {
5346 done
5447}
5548
49+ # ################### MAIN CODE ####################
50+
51+ validate_required_env_variables
52+
53+ auth_header=" Authorization: token ${GITHUB_TOKEN} "
54+
5655# extract meta information for current workflow run
57- exportAll " $( curl -s " ${GITHUB_API} /repos/${GITHUB_REPOSITORY} /actions/runs/${GITHUB_RUN_ID} " -H " ${auth_header} " -H " ${accept_header } " | extractMetaInformation | convertToKeyValuePairs) "
56+ exportAll " $( curl -s " ${GITHUB_API} /repos/${GITHUB_REPOSITORY} /actions/runs/${GITHUB_RUN_ID} " -H " ${auth_header} " -H " ${ACCEPT_HEADER } " | extractMetaInformation | convertToKeyValuePairs) "
5857echo " workflow id: ${workflow_id?} "
5958echo " branch: ${branch?} "
6059echo " repo: ${repo?} "
6160
6261# get the run ids for runs on same branch/repo
63- run_ids=$( curl -s " ${GITHUB_API} /repos/${GITHUB_REPOSITORY} /actions/workflows/${workflow_id} /runs" -H " ${auth_header} " -H " ${accept_header } " | getRunningWorkflowIds)
62+ run_ids=$( curl -s " ${GITHUB_API} /repos/${GITHUB_REPOSITORY} /actions/workflows/${workflow_id} /runs" -H " ${auth_header} " -H " ${ACCEPT_HEADER } " | getRunningWorkflowIds)
6463
6564echo " run ids: ${run_ids} "
6665
6766# cancel the previous runs
6867for run_id in $run_ids ; do
69- curl -s -X POST " ${GITHUB_API} /repos/${GITHUB_REPOSITORY} /actions/runs/${run_id} /cancel" -H " ${auth_header} " -H " ${accept_header } "
68+ curl -s -X POST " ${GITHUB_API} /repos/${GITHUB_REPOSITORY} /actions/runs/${run_id} /cancel" -H " ${auth_header} " -H " ${ACCEPT_HEADER } "
7069 echo " Cancelled run $run_id "
7170done
0 commit comments