How can I use git python get diffs

5.5k views Asked by At

I am trying to use GitPython to get me diffs in the format I want.

For every file I would like 3 lists. A list of lines that were changed, added, and removed.

I've been looking online and at the documentation and can't seem to figure out how to do this.

2

There are 2 answers

1
Jordan Reiter On BEST ANSWER

As far as I can tell, there is actually no way to do this.

You'd think they'd implement this functionality, but as far as I can tell file-level diffs are not implemented directly in GitPython.

The only way to retrieve changed lines within GitPython is using the git command directly, like so:

from git import Repo
repo = Repo('path/to/repo')
filename = 'path/to/repo/subdir/myfile'
diff_output = repo.git.diff(filename)

With diff_output now containing the same content you'd see if you did:

$ cd path/to/repo
$ git diff subdir/myfile

So it's not very useful. You're going to probably have to write your own code to parse the diff file to get the information you need.

Frustrating, because I'd like a similar functionality and it looks like my only option really is manually parsing git diffs.

I have to assume that GitPython is primarily used for managing changes to branches, etc and not inspecting or dealing with source code changes on the file level.

2
Abe On

See this documentation. It could be useful.