How to get staged files using GitPython?

萝らか妹 提交于 2019-12-08 15:53:20

问题


I'm counting staged files in git using GitPython.

For modified files, I can use

repo = git.Repo()
modified_files = len(repo.index.diff(None))

But for staged files I can't find the solution.

I know git status --porcelain but I'm looking for other solution which is better. (I hope using gitpython not git command, the script will be faster)


回答1:


You are close, use repo.index.diff("HEAD") to get files in staging area.


Full demo:

First create a test repo:

$ 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

Now check in 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


来源:https://stackoverflow.com/questions/31959425/how-to-get-staged-files-using-gitpython

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!