3

I'm new with GitPython and I would like to get the nomber of commits of a repo. I am looking to get alternative to "git rev-list --count HEAD" in GitPython, is there a specific function to do that ?

I tried to get the list of every commits of the repo to display then it's size, but the last commit only appears. thanks for help, Regards.

2 Answers 2

7

Try the code:

import git

repo_path = 'foo'
repo = git.Repo(repo_path)
# get all commits reachable from "HEAD"
commits = list(repo.iter_commits('HEAD'))
# get the number of commits
count = len(commits)

I'm not familiar with Python 3.x. There may be errors due to differences between Python 2.x and 3.x.

After doing some research, I find we can just invoke git rev-list --count HEAD in a direct way.

import git

repo_path = 'foo'
repo = git.Repo(repo_path)
count = repo.git.rev_list('--count', 'HEAD')

Note that the - in the command name should be _ in the code.

Sign up to request clarification or add additional context in comments.

2 Comments

First example with iter_commits might raise an exeption if there is no commit history (0 commits).
Your second answer was very helpful, particularly if the result is zero. In my case, I needed all commits and for a date range. count = repo.git.rev_list('--count', '--all', since='2023-02-01', until='2023-03-01') Thank you @ElpieKay.
0

You can get list of all commits with iter_commits(). Iterate over it and count commits

from git import Repo

repo = Repo()

print(len(list(repo.iter_commits())))

1 Comment

It works now ! thank a lot I didn't try that way before :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.