pythonpython-3.xgitgitpython

GitPython: get rename files as deleted and added


I need to get git diff files since specific commit using GitPython. As I understood I get renamed files using 'R' type . Is it possible to get the rename_from in the deleted lists and the rename_to in the added list?

I managed to do it this way:


commit = repo.commit(<commit_hash>)

# Deleted
for diff_del in commit.diff(commit.parents[0]).iter_change_type('D'):
    print(diff_del.a_path)

# Added
for diff_del in commit.diff(commit.parents[0]).iter_change_type('A'):
    print(diff_del.a_path)

# Renamed - No need, Files will be included in 'deleted' and 'added'
#for diff_mv in commit.diff(commit.parents[0]).iter_change_type('R'):
#    print(diff_mv.a_path)

# Modified
for diff_mod in commit.diff(commit.parents[0]).iter_change_type('M'):
    print(diff_mod.a_path)

I based on this question: https://stackoverflow.com/questions/68422402/extract-paths-to-modified-files-except-for-deleted-or-renamed-files


Solution

  • According to @Tim Roberts, renamed files must appear in 'R' section. Therefore I did this workaround:

    added = [diff.b_path for diff in changes.iter_change_type('A')]
    deleted = [diff.a_path for diff in changes.iter_change_type('D')]
    updated = [diff.a_path for diff in changes.iter_change_type('M')]
    
    for diff in changes.iter_change_type('R'):
        deleted.append(diff.a_path)
        added.append(diff.b_path)