Created
June 29, 2020 22:33
-
-
Save n8gray/48d0bf56778277bce594782af31a214d to your computer and use it in GitHub Desktop.
Delete branches that have been merged to the branch of your choice. Works with regular merges and squash merges.
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/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