加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

使用gitpython获取更改的文件

发布时间:2020-12-16 22:54:52 所属栏目:Python 来源:网络整理
导读:我想获得当前git-repo的已更改文件列表.这些文件通常列在“更改”下,不会进行提交:调用git status时. 到目前为止,我已设法连接到存储库,将其拉出并显示所有未跟踪的文件: from git import Reporepo = Repo(pk_repo_path)o = self.repo.remotes.origino.pul
我想获得当前git-repo的已更改文件列表.这些文件通常列在“更改”下,不会进行提交:调用git status时.

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

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

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

显然我可以调用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'

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读