GitPython – Diff between two branches

Code:

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_change_type('A'):
    new_files.append(file)

# Collection all deleted files
for file in diff_index.iter_change_type('D'):
    deleted_files.append(file)

# Collection all modified files
for file in diff_index.iter_change_type('M'):
    modified_files.append(file)

Analyze:

Let’s imagine the situation:

You are before code review and you need to get all changes between feature and develop with GitPython.
First you need to get last commits from two branches:
# Your last commit of the current branch
commit_dev = repo.head.commit.tree

# Your last commit of the dev branch
commit_origin_dev = repo.commit("origin/dev")

Then get your changes:

diff_index = commit_origin_dev.diff(commit_feature)

And at last get sort changes by type:


# Collection all new files
for file in diff_index.iter_change_type('A'):
    new_files.append(file)

# Collection all deleted files
for file in diff_index.iter_change_type('D'):
    deleted_files.append(file)

# Collection all modified files
for file in diff_index.iter_change_type('M'):
    modified_files.append(file)

Here you need to be careful, becase comparing commit_origin_dev with commit_feature and commit_feature with commit_origin_dev can give different results, when you are specify type change type.

More about:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s