使用gitpython获取更改的文件

Jak*_*ube 9 python gitpython

我想获得当前git-repo的已更改文件列表.这些文件通常在Changes not staged for commit:调用时列出git status.

到目前为止,我已设法连接到存储库,将其拉出并显示所有未跟踪的文件:

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

但现在我想显示所有有变化的文件(未提交).任何人都能把我推向正确的方向吗?我查看repo了一段时间的方法和实验的名称,但我找不到正确的解决方案.

显然我可以调用repo.git.status和解析文件,但这根本不优雅.必须有更好的东西.


编辑:现在我考虑一下.更有用的是一个函数,它告诉我单个文件的状态.喜欢:

print(repo.get_status(path_to_file))
>>untracked
print(repo.get_status(path_to_another_file))
>>not staged
Run Code Online (Sandbox Code Playgroud)

Bar*_*oży 15

for item in repo.index.diff(None):
    print item.a_path
Run Code Online (Sandbox Code Playgroud)

或者只获得清单:

changedFiles = [ item.a_path for item in repo.index.diff(None) ]
Run Code Online (Sandbox Code Playgroud)

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'
Run Code Online (Sandbox Code Playgroud)

  • @Ciastopiekarz文档说“无”意味着要与工作树进行比较,请参见http://gitpython.readthedocs.io/en/stable/reference.html?highlight=diffable#git.diff.Diffable.diff (3认同)
  • 你不应该将 `HEAD` 而不是 `None` 传递给 `diff` 函数吗? (2认同)

小智 6

只是为了赶上@ciasto piekarz 的问题:取决于你想展示的内容:

repo.index.diff(None)
Run Code Online (Sandbox Code Playgroud)

仅列出尚未暂存的文件

repo.index.diff('Head')
Run Code Online (Sandbox Code Playgroud)

仅列出暂存的文件