Last active
February 22, 2024 14:35
-
-
Save skjnldsv/ac9c7cc16698ee21f27389ad7d3185c2 to your computer and use it in GitHub Desktop.
A script to cancel all queued or running jobs for a given branch
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Cancel all jobs for a given repo and branch | |
# https://gist.github.com/skjnldsv/ac9c7cc16698ee21f27389ad7d3185c2 | |
# Checking token | |
[[ ! $GITHUB_TOKEN ]] && echo "GITHUB_TOKEN is not set or valid" && exit 1 | |
# Extracting flags | |
while getopts ":r:b:o:h" flag | |
do | |
case "${flag}" in | |
r) REPO=${OPTARG};; | |
b) BRANCH=${OPTARG};; | |
o) ORG=${OPTARG};; | |
h) HELP=true;; | |
\?) | |
echo "Invalid option: -$OPTARG" >&2 | |
exit 1 | |
;; | |
:) | |
echo "Option -$OPTARG requires an argument." >&2 | |
exit 1 | |
;; | |
esac | |
done | |
# Checking flags validity | |
[[ ! $REPO && ! $HELP ]] && echo "REPO is not set or valid" | |
[[ ! $BRANCH && ! $HELP ]] && echo "BRANCH is not set or valid" | |
[[ ! $ORG ]] && ORG=nextcloud | |
# New line when showing help after error messages | |
[[ (! $REPO || ! $BRANCH) && ! $HELP ]] && echo -e "" && HELP=true | |
# Help is on the way | |
if [[ $HELP ]]; then | |
echo "Usage: github_cancel_jobs.sh -r <repo> -b <branch> [-o <org>]" | |
echo " -r <repo> The repo to check for jobs" | |
echo " -b <branch> The branch to check for jobs" | |
echo " -o <org> The organization to check for jobs (default: nextcloud)" | |
echo " -h Show this help" | |
exit 0 | |
fi | |
# Fetching jobs | |
echo "Fetching jobs for repo $ORG/$REPO on $BRANCH..."; | |
JSON=$(curl --silent -H "Accept: application/vnd.github+json" \ | |
-H "Authorization: Bearer $GITHUB_TOKEN" \ | |
-X GET "https://api.github.com/repos/$ORG/$REPO/actions/runs?branch=$BRANCH&per_page=100") | |
JOBS=$(jq '.workflow_runs[]? | select((.status == "queued") or (.status == "in_progress")) | .id' <<< $JSON) | |
MESSAGE=$(jq '.message // empty' <<< $JSON) | |
# Checking error | |
if [[ $MESSAGE ]]; then | |
echo "Error: $MESSAGE" | |
exit 1 | |
fi | |
# Nothing to do, exiting | |
[[ -z "$JOBS" ]] && echo "No jobs to cancel" && exit 0 | |
# Cancelling jobs | |
COUNT=$(echo $JOBS | wc -w) | |
echo "Cancelling $COUNT jobs..."; | |
for id in $JOBS; do | |
curl --silent -H "Accept: application/vnd.github+json" \ | |
-H "Authorization: Bearer $GITHUB_TOKEN" \ | |
-X POST "https://api.github.com/repos/$ORG/$REPO/actions/runs/$id/force-cancel" > /dev/null | |
done | |
echo "Done !"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment