Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Delete branches that have been merged to the branch of your choice. Works with regular merges and squash merges.
#!/bin/sh
set -eo pipefail
BASE=origin/dev
if [[ $1 == "-d" ]]; then
DELETE=1
shift
fi
if [[ -n "$1" ]]; then
BASE=$1
#echo "base = $1"
fi
if [[ -z "$DELETE" ]]; then
echo "Finding branches merged to: $BASE"
echo "Run with -d to delete them"
else
echo "Deleting branches merged to: $BASE"
fi
echo
#-------------------------------------------------------
# Return success if the branch should be excluded
isExcluded()
{
case $1 in
master|hotfix|dev|RELEASE-*)
return 0
;;
*)
return 1
;;
esac
}
# Delete the branch or warn that it would be deleted
deleteBranch()
{
if [[ -z "$DELETE" ]]; then
echo "Would delete: $(git rev-parse --short $1) $1"
else
#echo "Deleting: $(git rev-parse --short $1) $1"
git branch -D $1
fi
}
#-------------------------------------------------------
# Regular merges
for branch in `git branch --merged $BASE`; do
isExcluded $branch && continue
deleteBranch $branch
done
# Cherry-picked branches
git for-each-ref refs/heads/ "--format=%(refname:short)" | while read branch; do
# Exclude branches we don't ever want to delete
isExcluded $branch && continue
mergeBase=$(git merge-base $BASE $branch)
if [[ $(git cherry $BASE $(git commit-tree $(git rev-parse $branch\^{tree}) -p $mergeBase -m _)) == "-"* ]]; then
deleteBranch $branch
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment