Extract paths to modified files except for deleted or renamed files

Viewed 117

I need to get the paths to the files that were changed in the last commit using GitPython. I managed to do it this way:

import os

from git import Repo


repo = Repo(os.path.dirname(sys.argv[0]))
commit = list(repo.iter_commits(max_count=1))[0]
files = commit.stats.files

for filepath in files:
   print(filepath)

But now I want to filter out those files that were deleted or renamed, and I'm a bit stuck with it. I would be grateful for any help, maybe someone has such an experience.

1 Answers

Use iter_change_type:

previous_commit = repo.commit('HEAD~1')

# Deleted
for diff_del in previous_commit.diff('HEAD').iter_change_type('D'):
    print(diff_del.a_path)

# Renamed
for diff_mv in previous_commit.diff('HEAD').iter_change_type('R'):
    print(diff_mv.a_path)

# Modified
for diff_mod in previous_commit.diff('HEAD').iter_change_type('M'):
    print(diff_mod.a_path)
Related