Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I delete all git branches which have been "Squash and Merge" via GitHub?

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 
like image 569
png Avatar asked Apr 19 '17 07:04

png


People also ask

Does squash and merge delete branch?

@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.

How do I delete a branch after merge in GitHub?

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.

Can you delete branches after merge?

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).


1 Answers

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

like image 124
Clay Avatar answered Oct 11 '22 19:10

Clay