I get bored looking through dozens and dozens of stale Git branches. If git branch --remote
takes up more than a screenful of text then I am unhappy!
Here are some shell hacks that can help you when trying to work out what can be deleted.
This shows you all the remote branches which are already merged, those can probably be deleted right away!
git branch --remote --merged
These are the remote branches that aren’t merged yet.
git branch --remote --no-merged
Best not to delete those straight away. But some of them are probably totally stale. This snippet will loop through each unmerged branch and tell you (a) when the last commit was made, and (b) how many commits it contains which are not merged to ‘origin/master’.
for b in $(git branch --remote --no-merged); do
echo $b;
git show $b --pretty="format: Last commit: %cd" | head -n 1;
echo -n " Commits from 'master': ";
git log --oneline $(git merge-base $b origin/master)..$b | wc -l;
echo;
done
The output looks like this:
origin/album-art-to-libtracker-extract
Last commit: Mon Mar 29 17:22:14 2010 +0100
Commits from 'master': 1
origin/albumart-qt
Last commit: Thu Oct 21 11:10:25 2010 +0200
Commits from 'master': 1
origin/api-cleanup
Last commit: Thu Feb 20 12:16:43 2014 +0100
Commits from 'master': 18
...
Two of those haven’t been touched for five years, and only contain a single commit! So they are probably good targets for deletion, for example.
You can also get the above info sorted, with the oldest branches first. First you need to generate a list. This outputs each branch and the date of its newest commit (as a number), sorts it numerically, then filters out the number and writes it to a file called ‘unmerged-branches.txt’:
for b in $(git branch --remote --no-merged); do
git show $b --pretty="format:%ct $b" | head -n 1;
done | sort -n | cut -d ' ' -f 2 > unmerged-branches.txt
Then you can run the formatting command again, but replace the first line with:
for b in $(cat unmerged-branches.txt); do
OK! You have a list of all the unmerged branches and you can send a mail to people saying you’re going to delete all of them older than a certain point unless they beg you not to.
One thought on “Cleaning up stale Git branches”