Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mass deleting local branches that has been rebased and merged

Tags:

git

github

in our team we keep the fast-forward only merge policy for master and development branches in order to prevent merge commit hell:

merge commit hell

I do not delete my topic branches once they are merged (or rebased and then merged), so I end up with tons of these. I can delete some:

git branch --merged

This will only show me those which hasn't been rebased prior merge. And there are some of these, I am able to clean them up.

I am looking for some strategy, script or hint how to deal with the rebased ones. There must be a script that finds all the commits from the topic branch in the master in a loop or something. Please share ;-)

Thanks

like image 713
lzap Avatar asked Jul 17 '14 09:07

lzap


3 Answers

I wanted something non-interactive that generalizes to more than one commit per branch. With the caveat that this hasn't been tested extensively yet, and may be assuming more than you do about the state of your clone when you run this:

Rebase all local branches that can be rebased cleanly:

REBASE_TARGET=upstream/master
for branch in $(git for-each-ref --format="%(refname:lstrip=2)" refs/heads/); do
    git rebase "$REBASE_TARGET" "$branch" || git rebase --abort
done

Remove any local branches that have been merged:

git branch --format="%(refname:lstrip=2)" --merged | xargs git branch -d
like image 85
wtanaka.com Avatar answered Oct 16 '22 18:10

wtanaka.com


You have one script which does that by:

  • getting the last commit of each branch
  • checking that commit is part of the history of master

That would delete rebased branches which have been merged to master.

last_commit_msg="$(git log --oneline --format=%f -1 $branch)"
if [[ "$(git log --oneline --format=%f | grep $last_commit_msg | wc -l)" -eq 1 ]]; then
like image 45
VonC Avatar answered Oct 16 '22 17:10

VonC


I wrote an interactive script that can help with this.

https://github.com/lzap/git-xcleaner

Send patches and read the warning from it's manual page (bellow)!

git xcleaner main menu

git-xcleaner(1) -- interactive git branch removal SYNOPSIS

git xcleaner

DESCRIPTION

This tool helps with deleting unused topic branches using TUI (text user interface). It also offers mechanisms for pre-selecting branches that can be safely removed.

WARNING

This tool deletes git branches after confirmation. There is no way back when git garbage is collected. Double check what you are about to remove!

RETURN VALUES

Zero on success, one on errors when manipulating with git.

BUGS

File bugs at https://github.com/lzap/git-xcleaner/issues

like image 41
lzap Avatar answered Oct 16 '22 17:10

lzap