Ever since GitHub introduced Squash and Merge, all the cool kids at my workplace are using it when merging pull requests. Is there a way to cleanup "Squash and Merge" branches?
The following command from How can I delete all git branches which have been merged? does not work for "Squash and Merge":
git branch --merged | egrep -v "(^\*|master|dev)" | xargs git branch -d
@Alec: With squash merges, generally the correct thing is to delete the branch you've just merged, losing all the commits you've just traded in for a single squash-commit.
On GitHub.com, navigate to the main page of the repository. Under your repository name, click Settings. Under "Pull Requests", select or unselect Automatically delete head branches.
There's no problem in deleting branches that have been merged in. All the commits are still available in the history, and even in the GitHub interface, they will still show up (see, e.g., this PR which refers to a fork that I've deleted after the PR got accepted).
Here's a script that will delete all local branches that have been squash merged into master:
git checkout -q master && git for-each-ref refs/heads/ "--format=%(refname:short)" | while read branch; do mergeBase=$(git merge-base master $branch) && [[ $(git cherry master $(git commit-tree $(git rev-parse "$branch^{tree}") -p $mergeBase -m _)) == "-"* ]] && git branch -D $branch; done
If you want to run a dry run, you can instead run this:
git checkout -q master && git for-each-ref refs/heads/ "--format=%(refname:short)" | while read branch; do mergeBase=$(git merge-base master $branch) && [[ $(git cherry master $(git commit-tree $(git rev-parse "$branch^{tree}") -p $mergeBase -m _)) == "-"* ]] && echo "$branch is merged into master and can be deleted"; done
You can then setup an alias like this:
alias gprunesquashmerged='git checkout -q master && git for-each-ref refs/heads/ "--format=%(refname:short)" | while read branch; do mergeBase=$(git merge-base master $branch) && [[ $(git cherry master $(git commit-tree $(git rev-parse "$branch^{tree}") -p $mergeBase -m _)) == "-"* ]] && git branch -D $branch; done'
Source:
https://github.com/not-an-aardvark/git-delete-squashed
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With