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 Overflow
🌐
Readthedocs
gitpython.readthedocs.io › en › stable › tutorial.html
GitPython Tutorial — GitPython 3.2.1 documentation
To use it, set the name of the branch you want to track to the submodule.$name.branch option of the .gitmodules file, and use GitPython update methods on the resulting repository with the to_latest_revision parameter turned on. In the latter case, the sha of your submodule will be ignored, instead a local tracking branch will be updated to the respective remote branch automatically, provided there are no local changes. The resulting behaviour is much like the one of svn::externals, which can be useful in times. Diffs can generally be obtained by subclasses of Diffable as they provide the diff method.
Author: DHDaniel
🌐
Libelli
bbengfort.github.io › posts › extracting diffs from git with python
Extracting Diffs from Git with Python | Libelli
May 6, 2016 - Moreover, by using the GitPython library you have direct access to Git repositories that is scriptable.
Top answer
1 of 2
14

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').

2 of 2
0

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("")
Find elsewhere
🌐
Tim Santeford
timsanteford.com › posts › creating-a-git-like-diff-viewer-in-python-using-difflib
Creating a Git-Like Diff Viewer in Python Using Difflib - Tim Santeford
January 5, 2025 - Highlight additions in green and removals in red, mimicking Git’s style. Optionally show hints where character-level changes occur. Python’s difflib module offers multiple ways to compare text.
🌐
Florian-dahlitz
florian-dahlitz.de › articles › create-your-own-diff-tool-using-python
Create Your Own Diff-Tool Using Python - Florian Dahlitz
Without further introduction, let's jump in! The Python standard library contains a module called difflib. According to the documentation, this module provides classes and functions for comparing sequences.
🌐
Wordpress
iliasjavascriptjourney.wordpress.com › 2022 › 02 › 16 › gitpython-diff-between-two-branches
GitPython – Diff between two branches – Ilia's Airflow, Python, PostgreSQL, Javascript Journey
April 25, 2022 - On February 16, 2022April 25, 2022 By Илья КатигаридиIn Python, Uncategorized · import os from pathlib import Path from git import Repo # path to repo folder path = Path(os.path.dirname(os.path.abspath(__file__))) # repo variable repo = Repo(path) # Your last commit of the current branch commit_feature = repo.head.commit.tree # Your last commit of the dev branch commit_origin_dev = repo.commit("origin/dev") new_files = [] deleted_files = [] modified_files = [] # Comparing diff_index = commit_origin_dev.diff(commit_feature) # Collection all new files for file in diff_index.iter_c
🌐
Readthedocs
gitpython.readthedocs.io › en › 0.1.7 › reference.html
API Reference — GitPython 0.1.7 documentation
Represents a git repository and allows you to query references, gather commit information, generate diffs, create and clone repositories query the log.
🌐
Readthedocs
gitpython.readthedocs.io › en › stable › reference.html
API Reference — GitPython 3.2.1 documentation
We only document the parameters that differ from IndexObject. ... parent_commit – The Commit whose tree is supposed to contain the .gitmodules blob, or None to always point to the most recent commit.
🌐
PyPI
pypi.org › project › git-diff-tool
git-diff-tool · PyPI
Python :: 3 · Report project as malware · Welcome to Git Diff Tool! A simple yet powerful command-line utility designed to compare two branches of a Git repository and save their differences into a file.
      » pip install git-diff-tool
    
Published: Oct 13, 2024
Version: 1.0.0
🌐
Pygit2
pygit2.org › diff.html
Diff — pygit2 1.19.3 documentation
Parses a git unified diff into a diff object without a repository
🌐
GitHub
gist.github.com › KaoruNishikawa › 55781991af9d50494dd85ac6db0cad89
Print Git-like diff of arbitrary 2 strings in Python · GitHub
Print Git-like diff of arbitrary 2 strings in Python · Raw · diff.py · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
🌐
Tekin
tekin.co.uk › 2020 › 10 › better-git-diff-output-for-ruby-python-elixir-and-more
Better Git diff output for Ruby, Python, Elixir, Go and more | tekin.co.uk
October 16, 2020 - Some open source projects define their own .gitattributes file. There’s one in Rails. There’s even one in the Git source that enables the diff patterns for Perl and Python.
🌐
Kanoe
kanoe.studio › archives › 993
GitPythonでdiffをとる方法 · Kanoe Studio Kanoe Studio
December 12, 2019 - 例えば、repo.git.diff(HEAD^) にすることで、最新のコミットとその一個前のコミットのdiffをとることができます。