gitpython and git diff

user1816561 picture user1816561 · Nov 19, 2013 · Viewed 27.3k times · Source

I am looking to get only the diff of a file changed from a git repo. Right now, I am using gitpython to actually get the commit objects and the files of git changes, but I want to do a dependency analysis on only the parts of the file changed. Is there any way to get the git diff from git python? Or am I going to have to compare each of the files by reading line by line?

Answer

Cairo picture Cairo · Apr 27, 2014

You can use GitPython with the git command "diff", just need to use the "tree" object of each commit or the branch for that you want to see the diffs, for example:

repo = Repo('/git/repository')
t = repo.head.commit.tree
repo.git.diff(t)

This will print "all" the diffs for all files included in this commit, so if you want each one you must iterate over them.

With the actual branch it's:

repo.git.diff('HEAD~1')

Hope this help, regards.