Skip to content

Instantly share code, notes, and snippets.

@michmzr
Created July 15, 2024 14:20
Show Gist options
  • Save michmzr/ba3cccbe6366115cd6b97110088ad49e to your computer and use it in GitHub Desktop.
Save michmzr/ba3cccbe6366115cd6b97110088ad49e to your computer and use it in GitHub Desktop.
Cancel all queued/in_progress github runs associated with branch
#!/usr/bin/env zsh
# Script Name: cancel_github_workflows.zsh
# Description: This script cancels GitHub Actions workflows for a specific branch
# that are either queued or in progress.
#
# Usage: ./cancel_github_workflows.zsh <branch_name>
#
# Arguments:
# <branch_name>: The name of the branch for which to cancel workflows
#
# Requirements:
# - GitHub CLI (gh) must be installed and authenticated
# - The script must be run from the directory containing the GitHub repository
#
# Example:
# ./cancel_github_workflows.zsh feature/new-feature
#
# Note: This script will cancel ALL queued and in-progress workflows for the specified branch.
# Use with caution.
# cd [project directory with .git] # Change to the directory where ther epository is located
# Check if a number is provided
if [[ $# -eq 0 ]]; then
echo "Please provide a number to search for in workflow names."
exit 1
fi
# The number to search for in workflow names
branch_name=$1
# Function to cancel a workflow run
cancel_workflow() {
local run_id=$1
local workflow_name=$2
echo "Cancelling workflow: $workflow_name (Run ID: $run_id)"
gh run cancel $run_id
if [[ $? -eq 0 ]]; then
echo "Successfully cancelled workflow: $workflow_name (Run ID: $run_id)"
else
echo "Failed to cancel workflow: $workflow_name (Run ID: $run_id)"
fi
}
# Get pending and in-progress workflows
echo "Fetching pending and in-progress workflows..."
workflows=$(gh run list --json databaseId,name,status,displayTitle --branch $1 --jq '.[] | select(.status == "queue" or .status == "in_progress") | [.databaseId, .name, .status, .displayTitle] | @tsv')
# Counter for cancelled workflows
cancelled_count=0
# Process each workflow
echo "$workflows" | while IFS=$'\t' read -r id name; do
cancel_workflow $id "$name"
((cancelled_count++))
done
echo "Total workflows cancelled: $cancelled_count"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment