python - 使用 gitpython 获取更改的文件

标签 python gitpython

我想获取当前 git-repo 的更改文件列表。调用 git status 时,通常在 Changes not staged for commit: 下列出的文件。

到目前为止,我已经成功连接到存储库,拉取它并显示所有未跟踪的文件:

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

但现在我想显示所有有更改(未提交)的文件。有人能把我推向正确的方向吗?我查看了repo的方法名,试验了一段时间,没有找到正确的解决方案。

显然我可以调用 repo.git.status 并解析文件,但这一点也不优雅。必须有更好的东西。


编辑:现在我想到了。更有用的是一个函数,它告诉我单个文件的状态。喜欢:

print(repo.get_status(path_to_file))
>>untracked
print(repo.get_status(path_to_another_file))
>>not staged

最佳答案

for item in repo.index.diff(None):
    print item.a_path

或者只获取列表:

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

repo.index.diff() 返回 http://gitpython.readthedocs.io/en/stable/reference.html#module-git.diff 中描述的 git.diff.Diffable

所以函数看起来像这样:

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'

关于python - 使用 gitpython 获取更改的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33733453/

相关文章:

python - django、pyenv、uwsgi - ModuleNotFoundError : No module named 'django'

python - 加速 Pandas 滚动引用另一个数据框

python - gitpython 和 git diff

python3 + pygit : "No module named ' repository'"

python - 如何使用 GitPython pull 远程存储库?

python - 当字典的长度/顺序发生变化时,如何从字典列表中提取特定值

python - 从 Python 读取 FoxPro DBF 文件的最简单方法是什么?

git push使用python

python - 如果在 for 循环中不工作,即使条件满足

python - 在 GitPython 中 checkout 或列出远程分支