Created
June 2, 2023 15:09
-
-
Save ohnit/b16bb922dfee33d7217b053bbb418b11 to your computer and use it in GitHub Desktop.
git-delete-remote-branches
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 | |
set -e -o pipefail | |
# Interactive script for deleting remote branches. Focused on branches left over | |
# when someone else merged or squash-merged a pull request, but did not delete | |
# the remote branch. | |
# | |
# Presents remote branches for a repo, one at a time. So you can decide whether | |
# to delete them. | |
# | |
# For each remote branch, it checks for commit messages on your current branch | |
# which has the remote branch's name in them and a shows a short commit graph | |
# to help you decide (maybe that merge commit is near the remote branch's head). | |
confirm() | |
{ | |
local response | |
# call with a prompt string or use a default | |
read -r -n 1 -p "${1:-Are you sure? [y/N]} " response | |
echo | |
case "${response}" in | |
[yY]) | |
true;; | |
q) | |
exit;; | |
*) | |
false;; | |
esac | |
} | |
for branch in $(git branch -r | awk '$1 ~ /^origin/ && $1 !~ /HEAD/ { sub(/^ *origin\//, ""); print }'); do | |
echo | |
echo "-------------- START: branch '${branch}'" | |
echo | |
echo "Any merge commits?:" | |
matches="$(git log --oneline --grep="$branch")" | |
if [ -n "$matches" ]; then | |
echo " yep!" | |
echo | |
echo "$matches" | |
echo | |
echo "log graph:" | |
commit_hash="$(git rev-parse "refs/remotes/origin/${branch}")" | |
merge_hash="$(git log --oneline --grep="$branch" | awk 'NR == 1 {print $1}')" | |
git log --graph --pretty=format:"%C(yellow)%h%Creset %ad %C(yellow)[%an]%Creset %Cgreen%d%Creset %s" --date=short -n 30 "$commit_hash" "$merge_hash" | |
if confirm "Delete remote branch?: '${branch}' [y/N] "; then | |
git push origin -d "${branch}" | |
fi | |
else | |
echo " nope!" | |
echo " skipping..." | |
fi | |
echo | |
echo | |
echo "-------------- END: branch '${branch}'" | |
echo | |
sleep 1 | |
tput -x clear | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment