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)
simply typing git status gives you a list of staged files, a list of modified yet unstaged files, and a list of untracked files.
The staging happens inside . git/index and . git/objects . The former contains the paths and the latter contains the file content.
GitPython is a python library used to interact with git repositories. It is a module in python used to access our git repositories. It provides abstractions of git objects for easy access of repository data, and additionally allows you to access the git repository more directly using pure python implementation.
You are close, use repo.index.diff("HEAD")
to get files in staging area.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With