If you want to access the contents of the diff, try this:
repo = git.Repo(repo_root.as_posix())
commit_dev = repo.commit("dev")
commit_origin_dev = repo.commit("origin/dev")
diff_index = commit_origin_dev.diff(commit_dev)
for diff_item in diff_index.iter_change_type('M'):
print("A blob:\n{}".format(diff_item.a_blob.data_stream.read().decode('utf-8')))
print("B blob:\n{}".format(diff_item.b_blob.data_stream.read().decode('utf-8')))
This will print the contents of each file.
Answer from D. A. on Stack OverflowIf you want to access the contents of the diff, try this:
repo = git.Repo(repo_root.as_posix())
commit_dev = repo.commit("dev")
commit_origin_dev = repo.commit("origin/dev")
diff_index = commit_origin_dev.diff(commit_dev)
for diff_item in diff_index.iter_change_type('M'):
print("A blob:\n{}".format(diff_item.a_blob.data_stream.read().decode('utf-8')))
print("B blob:\n{}".format(diff_item.b_blob.data_stream.read().decode('utf-8')))
This will print the contents of each file.
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.
import git
repo = git.Repo('repo_path')
commits_list = list(repo.iter_commits())
# --- To compare the current HEAD against the bare init commit
a_commit = commits_list[0]
b_commit = commits_list[-1]
a_commit.diff(b_commit)
This will return a diff object for the commits. There are other ways to achieve this as well. For example (this is copy/pasted from http://gitpython.readthedocs.io/en/stable/tutorial.html#obtaining-diff-information):
```
hcommit = repo.head.commit
hcommit.diff() # diff tree against index
hcommit.diff('HEAD~1') # diff tree against previous tree
hcommit.diff(None) # diff tree against working tree
index = repo.index
index.diff() # diff index against itself yielding empty diff
index.diff(None) # diff index against working copy
index.diff('HEAD') # diff index against current HEAD tree
```
To get the contents of the diff:
import git
repo = git.Repo("path/of/repo/")
# define a new git object of the desired repo
gitt = repo.git
diff_st = gitt.diff("commitID_A", "commitID_B")
Update:
I found my old answer is not working anymore. Here is the new solution:
For this solution, you need git and unidiff packages.
import git
from unidiff import PatchSet
from cStringIO import StringIO
commit_sha1 = 'commit_sha'
repo_directory_address = "your/repo/address"
repository = git.Repo(repo_directory_address)
commit = repository.commit(commit_sha1)
uni_diff_text = repository.git.diff(commit_sha1+ '~1', commit_sha1,
ignore_blank_lines=True,
ignore_space_at_eol=True)
patch_set = PatchSet(StringIO(uni_diff_text), encoding='utf-8')
change_list = [] # list of changes
# [(file_name, [row_number_of_deleted_line],
# [row_number_of_added_lines]), ... ]
for patched_file in patch_set:
file_path = patched_file.path # file name
print('file name :' + file_path)
del_line_no = [line.target_line_no
for hunk in patched_file for line in hunk
if line.is_added and
line.value.strip() != ''] # the row number of deleted lines
print('deleted lines : ' + str(del_line_no))
ad_line_no = [line.source_line_no for hunk in patched_file
for line in hunk if line.is_removed and
line.value.strip() != ''] # the row number of added liens
print('added lines : ' + str(ad_line_no))
change_list.append((file_path, del_line_no, ad_line_no))
Old Solution (This solution may not work anymore)
Finally, I found the solution. The output of gitpython is a little bit different from the standard git diff output. In the standard git diff source file start with --- but the output of gitpython start with ------ as you can see in the out put of running the following python code (this example is generated with elasticsearch repository):
import git
repo_directory_address = '/your/elasticsearch/repository/address'
revision = "ace83d9d2a97cfe8a8aa9bdd7b46ce71713fb494"
repository = git.Repo(repo_directory_address)
commit = repository.commit(rev=revision)
# Git ignore white space at the end of line, empty lines,
# renamed files and also copied files
diff_index = commit.diff(revision+'~1', create_patch=True, ignore_blank_lines=True,
ignore_space_at_eol=True, diff_filter='cr')
print reduce(lambda x, y: str(x)+str(y), diff_index)
The partial out put would be as follow:
core/src/main/java/org/elasticsearch/action/index/IndexRequest.java
=======================================================
lhs: 100644 | f8b0ce6c13fd819a02b1df612adc929674749220
rhs: 100644 | b792241b56ce548e7dd12ac46068b0bcf4649195
------ a/core/src/main/java/org/elasticsearch/action/index/IndexRequest.java
+++ b/core/src/main/java/org/elasticsearch/action/index/IndexRequest.java
@@ -20,16 +20,18 @@
package org.elasticsearch.action.index;
import org.elasticsearch.ElasticsearchGenerationException;
+import org.elasticsearch.Version;
import org.elasticsearch.action.ActionRequestValidationException;
import org.elasticsearch.action.DocumentRequest;
import org.elasticsearch.action.RoutingMissingException;
import org.elasticsearch.action.TimestampParsingException;
import org.elasticsearch.action.support.replication.ReplicationRequest;
import org.elasticsearch.client.Requests;
+import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.metadata.MappingMetaData;
import org.elasticsearch.cluster.metadata.MetaData;
import org.elasticsearch.common.Nullable;
-import org.elasticsearch.common.UUIDs;
+import org.elasticsearch.common.Strings;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.bytes.BytesReference;
As you can see the line 4 of the source file start with ------. To fix the problem, you need to edit the regular expression in the source file of unidiff 0.5.2 which you find in /unidiff/constants.py from :
RE_SOURCE_FILENAME = re.compile(
r'^--- (?P<filename>[^\t\n]+)(?:\t(?P<timestamp>[^\n]+))?')
to:
RE_SOURCE_FILENAME = re.compile(
r'^------ (?P<filename>[^\t\n]+)(?:\t(?P<timestamp>[^\n]+))?')
PS: if the source file renamed, gitpython generates diff start with ---. But it will not throw an error because I filtered git diff of rename file (diff_filter='cr').
Use diff_index[i].diff as tdihp recommended and also add source and target file lines to the diff, othewise unidiff will throw. Here is my working code sample:
diffs = []
diff_index = commit.diff(prev_commit, create_patch=True)
for diff in diff_index.iter_change_type('M'):
if diff.a_path[-3:] == ".js":
diffs.append(diff)
if diffs:
for d in diffs:
a_path = "--- " + d.a_rawpath.decode('utf-8')
b_path = "+++ " + d.b_rawpath.decode('utf-8')
# Get detailed info
patch = PatchSet(a_path + os.linesep + b_path + os.linesep + d.diff.decode('utf-8'))
for h in patch[0]:
for l in h:
print(" " + str(l.source_line_no) + " <-> " + str(l.target_line_no))
print("")
» pip install git-diff-tool
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.
See this documentation. It could be useful.