Get changed files using gitpython
Asked Answered
E

2

30

I want to get a list of changed files of the current git-repo. The files, that are normally listed under Changes not staged for commit: when calling git status.

So far I have managed to connected to the repository, pulled it and show all untracked files:

from git import Repo
repo = Repo(pk_repo_path)
o = self.repo.remotes.origin
o.pull()[0]
print(repo.untracked_files)

But now I want to show all files, that have changes (not commited). Can anybody push me in the right direction? I looked at the names of the methods of repo and experimented for a while, but I can't find the correct solution.

Obviously I could call repo.git.status and parse the files, but that isn't elegant at all. There must be something better.


Edit: Now that I think about it. More usefull would be a function, that tells me the status for a single file. Like:

print(repo.get_status(path_to_file))
>>untracked
print(repo.get_status(path_to_another_file))
>>not staged
Eboh answered 16/11, 2015 at 10:45 Comment(1)
Possible duplicate of How to get staged files using GitPython?Eboh
E
54
for item in repo.index.diff(None):
    print(item.a_path)

or to get just the list:

changedFiles = [item.a_path for item in repo.index.diff(None)]

repo.index.diff() returns git.diff.Diffable described in http://gitpython.readthedocs.io/en/stable/reference.html#module-git.diff

So the function can look like this:

def get_status(repo, path):
    changed = [item.a_path for item in repo.index.diff(None)]
    if path in repo.untracked_files:
        return "untracked"
    elif path in changed:
        return "modified"
    else:
        return "don't care"
Edroi answered 14/3, 2017 at 17:1 Comment(5)
Are you not supposed to pass HEAD instead of None to diff function ?Toucan
@Ciastopiekarz The documentation says that None means to compare against the working tree, see gitpython.readthedocs.io/en/stable/…Plugugly
This does not return new added files @EdroiCordle
I have not been able to get a list of files that changed since the last pull using this method.Trierarch
same here, not returning anythinOmmatophore
D
6

just to catch up on @ciasto piekarz question: depending on what you want to show:

repo.index.diff(None)

does only list files that have not been staged

repo.index.diff('Head')

does only list files that have been staged

Delouse answered 16/11, 2021 at 14:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.