如何使用GitPython获取暂存文件?

Ken*_*ada 10 python git gitpython

我正在使用GitPython计算git中的暂存文件.

对于修改过的文件,我可以使用

repo = git.Repo()
modified_files = len(repo.index.diff(None))
Run Code Online (Sandbox Code Playgroud)

但对于分阶段文件,我找不到解决方案.

我知道,git status --porcelain但我正在寻找更好的其他解决方案.(我希望使用gitpython不是git命令,脚本会更快)

mu *_*u 無 13

你很近,用于repo.index.diff("HEAD")获取暂存区域中的文件.


完整演示:

首先创建一个测试回购:

$ cd test
$ mkdir repo && cd repo && touch a b c && git init && git add . && git commit -m "init"
$ echo "a" > a && echo "b" > b && echo "c" > c && git add a b
$ git status
On branch master
Changes to be committed:
        modified:   a
        modified:   b
Changes not staged for commit:
        modified:   c
Run Code Online (Sandbox Code Playgroud)

现在检查ipython:

$ ipython
In [1]: import git
In [2]: repo = git.Repo()
In [3]: count_modified_files = len(repo.index.diff(None))
In [4]: count_staged_files = len(repo.index.diff("HEAD"))
In [5]: print count_modified_files, count_staged_files
1 2
Run Code Online (Sandbox Code Playgroud)