Git diff against master branch using GitPython

118 views Asked by At

I must be dense, but I haven't been able to find a solution yet.

I am trying to get a list of all of the members (in all commits or not committed yet) that have changed on a branch in my Python program. On the command line, I use "git diff --name-only master" which does exactly what I want.

By using:

commit = repo.head.commit
master = repo.heads.master
for member in commit.diff(master).iter_change_type("M"):
    members.append(member.a_path)

I get a list of modified members from the latest commit. It does not include anything from prior commits or anything that hasn't been committed yet (I also do the same command with type "A" for anything added, I'm not worried about renames or deletes yet).

This works:

member_list = repo.git.diff("--name-only", "master").splitlines()

Which returns what I want, but it seems there should be a more "pythonic" way of doing this.

1

There are 1 answers

0
Madghostek On

You can use a_path attribute of Diff object, it's the path of file that differs on the "a" side, which is current branch, this is what the command prints as well.

import git

repo = git.Repo("path/to/repo")

for diff in repo.head.commit.diff('master'):
    print(diff.a_path)