2015-11-16 104 views
4

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

到目前为止,我已经成功地连接到存储库,把它和显示所有未跟踪文件:

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

但现在我想告诉所有的文件,有变化(不COMMITED)。任何人都能把我推向正确的方向吗?我查看了repo方法的名称并尝试了一段时间,但我找不到正确的解决方案。

显然我可以打电话repo.git.status并解析这些文件,但那根本不算优雅。必须有更好的东西。


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

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

可能的重复[如何使用GitPython获取分阶段文件?](http://stackoverflow.com/questions/31959425/how-to-get-staged-files-using-gitpython) – user38034

回答

3
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()返回git.diff.Diffable在http://gitpython.readthedocs.io/en/stable/reference.html#module-git.diff描述

这样的功能可以看看像这样:

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' 
+0

你不应该通过'HEAD'而不是'无'到'diff'功能? –

+0

@Ciastopiekarz文档说'None'意味着与工作树进行比较,参见http://gitpython.readthedocs.io/en/stable/reference.html?highlight=diffable#git.diff.Diffable.diff –

相关问题