Search code examples
gitgit-commit

How to get the count of number of commits of a specific branch?


I am trying to figure out if there is a way to get the count of the number of commits done on a specific branch.

I have tried using rev-list, but the count I am getting is different.

PS C:\Dev\code\TestProj> git checkout master
Already on 'master'                            
Your branch is up to date with 'origin/master'.
PS C:\Dev\code\TestProj> git checkout -B "TESTBRANCH"
Switched to a new branch 'TESTBRANCH'
PS C:\Dev\code\TestProj> git commit -a -m "TESTBRANCH-TEST COMMIT"
[TESTBRANCH 3a98967] TESTBRANCH-TEST COMMIT
 1 file changed, 1 insertion(+)            
PS C:\Dev\code\TestProj> git rev-list --count --first-parent TESTBRANCH
9
PS C:\Dev\code\TestProj> 

In the above code, I have made only one commit on the new branch which I created and I can see the count returned is 9. I think Git is taking into consideration some other revisions as well.

Is there a way to get the commit count as just 1?


Solution

  • In this case, you'll want to use a commit range from master to TESTBRANCH. This will count all commits made on TESTBRANCH since it diverged from master:

    git rev-list --count --first-parent master..TESTBRANCH
    

    The answer to this should be 1.

    If you pull later, and there are new commits on master, you can also count the number of commits since TESTBRANCH was created just by flipping the order of the arguments in the range:

    git rev-list --count --first-parent TESTBRANCH..master
    

    This syntax, of <branch A>..<branch B>, is called a commit range. For a more in-depth explanation, see this article on commit ranges, although a short summary would be:

    <branch A>..<branch B> refers to all the commits on branch B, that aren't on branch A. So master..TESTBRANCH means "all the commits on TESTBRANCH, that aren't on master".