sleske
sleske

Reputation: 83635

How to list only active / recently changed branches in git?

I sometimes work with source code repositories containing many branches, most of which are old and usually no longer relevant.

In these cases, the full list of branches from git branch is not very helpful. Is there a way to only list "active" branches? For example, only branches that received commits in the last n days? Ideally, the list would include the last commit date for each branch, and indicate if the branch is already fully merged.

P.S.: I realize that this can also be solved by deleting "old" branches (as discussed e.g. in What to do with experimental non-merged git branches? ), but this may not always be practical or accepted on a given project.

Upvotes: 27

Views: 8823

Answers (2)

Michał Politowski
Michał Politowski

Reputation: 4385

You can use git-for-each-ref to get a list of all the local and tracking branches sorted in descending order by the committer date of the last commit like this:

git for-each-ref --sort=-committerdate --format='%(committerdate:short) %(refname)' refs/heads refs/remotes

This outputs eg.:

2012-06-23 refs/heads/master
2012-06-21 refs/remotes/origin/HEAD
2012-06-21 refs/remotes/origin/master

You can add --count=m to get at most m branches, you can --sort=-authordate instead of using the committer date, you can of course use different formats. for-each-ref itself does not limit the result by date, this has to be scripted separately, but at least you have the dates from the commit object in hand.

Upvotes: 38

jkrcma
jkrcma

Reputation: 1202

ls -1 --sort=time .git/refs/heads/ | while read b; do PAGER='' git log -n1 --color --pretty=format:'%C(yellow)%d%Creset - %Cred%h%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset%n' --abbrev-commit $b --; done;

This oneliner prints all local branches sorted by time from newest to oldest. Each branch has last commit with human readable date string. You can add it to your .gitconfig.

For remote branches I came up with this creepy solution:

git ls-remote -h origin | while read b; do PAGER='' git log -n1 --color --pretty=format:'%ct%C(yellow)%d%Creset - %Cred%h%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset%n' --abbrev-commit $( echo $b | cut -d' ' -f1 ) --; done | sort -rn -k1,10 | cut -c11-

Edit: the more I think, the more I am afraid this could be unreliable, because ls-remote always connects to remote side whereas log not. It may require to do fetch before every run of this command.

Upvotes: 7

Related Questions