Search code examples
pythongitgitpython

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)


Solution

  • 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