Tuesday, May 6, 2014

Sorting remote Git branches in reverse commit order

Small, but useful Git + Perl command:


for k in `git branch -r | perl -pe 's/^..(.*?)( ->.*)?$/\1/'`; do echo -e `git show --pretty=format:"%Cgreen%ci %Cblue%cr%Creset %aN" $k -- | head -n 1`\\t$k; done | sort -r

It will sort all remote Git branches in reverse order by commit date. The result looks like this:

2014-05-06 10:18:29 +0200 33 minutes ago origin/master
2014-05-06 10:18:29 +0200 33 minutes ago origin/HEAD
2014-05-05 19:10:50 +0200 16 hours ago origin/the-hot-branch
...
2014-05-01 18:33:08 +0200 5 days ago origin/less-recent-branch
...
2014-01-27 15:44:27 +0100 3 months ago origin/totally-forgotten branch


Found on SO who quoted it from there.

One useful modification: also show the last committer:

for k in `git branch -r | perl -pe 's/^..(.*?)( ->.*)?$/\1/'`; do echo -e `git show --pretty=format:"%Cgreen%ci %Cblue%cr%Creset %aN" $k -- | head -n 1`\\t$k; done | sort -r

And don't forget to call first:

git fetch -p

to prune away the zombie branch references.

Then you can easily grep for someone's stale branches :)