Ian Livingstone
Ian Livingstone

Reputation: 261

Git Python Cannot find Commit

I am not able to find a commit that a tag points to by navigating the commit tree. For this specific example, I am using the Tornado Web repository cloned directly from Github.

import sys
import git

if len(sys.argv) < 2:
    print 'python git_test.py <repo path>'
    sys.exit(0)

repo = git.Repo(sys.argv[1])
commits = {}

for git_commit in repo.iter_commits():
    commits[git_commit.hexsha] = git_commit

print len(commits)

for git_tag in repo.tags:
    print 'Tag %s points to Commit %s' % (
        git_tag.name,
        commits[git_tag.commit.hexsha]
    )

This is suppose to find all commits in git's direct acyclic graph, however, I tried another approach that recursively navigated the dag through a recursive function and it delivered the same results.

ian@ian-EP45-UD3L:~/code/playground$ python git_test.py ~/code/tornado/
459
Tag v1.0.0 points to Commit eb5b3d8df7a305ac1ffa0a12c813e5d7ee4d6cd3
Traceback (most recent call last):
  File "git_test.py", line 19, in <module>
    commits[git_tag.commit.hexsha]
KeyError: '2b5064b7ed962603ade0db0c8e21846a9879e30e'

Am I doing something incorrectly, how can I work around this problem? Any help is appreciated!

I am using git-python v0.3.1.

Upvotes: 2

Views: 2267

Answers (1)

manojlds
manojlds

Reputation: 301477

I had not used gitpython before, so I was curious and tried your script on a dummy repo. I did not get any error and the tags printed properly. But I had a suspicion though:

I added a branch, added a commit, and tagged it. Then it gave the error you were getting, and things became obvious.

repo.iter_commits() only gets the commits in the current branch. So any tag to a commit in another branch won't have the commit in commits. I tried changing the branch to the new branch I created, and it failed saying a different commit was not found, which was of course in the master in my dummy repo.

That is your issue. You need to find a way to get all commits from all branches.

PS: You do know that you are going about a roundabout way to get the commit that a tag points to right?

Upvotes: 5

Related Questions