Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get staged files using GitPython?

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)

like image 822
Kentaro Wada Avatar asked Aug 12 '15 08:08

Kentaro Wada


People also ask

How do I list a staged file?

simply typing git status gives you a list of staged files, a list of modified yet unstaged files, and a list of untracked files.

Where are git staged files?

The staging happens inside . git/index and . git/objects . The former contains the paths and the latter contains the file content.

What is GitPython?

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.


1 Answers

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
like image 191
Anshul Goyal Avatar answered Sep 19 '22 15:09

Anshul Goyal