How to get staged files using GitPython?
Asked Answered
H

1

18

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)

Hanson answered 12/8, 2015 at 8:3 Comment(0)
A
26

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
Atomicity answered 12/8, 2015 at 9:0 Comment(4)
len(repo.index.diff("HEAD")) breaks on a repo with no commits. Is there any way around this?Stark
@Stark "breaks" is not a useful description of the problem you saw. There's a good chance that if you think in useful descriptions, something like "throws an exception", you could figure out how to resolve this on your own.Bullshit
@Bullshit Sure, I'll agree that "throws an exception" is a better description than "breaks". My point was purely that this answer (while excellent for most cases) does not solve the problem if you don't have a valid HEAD. (e.g. in a repo with no commits). Having staged files in a repo with no HEAD is a valid state and catching the exception that is thrown by running the code in the answer does not help in this scenario. Rather than nitpicking over semantics, it would be much more valuable if you suggested an alternative rather than commenting "figure it out yourself" on a literal Q&A website.Stark
@Stark It's not nit-picking over terminology; welcome to computer science where precision matters in communication. If you want an answer to your problem though you need to properly post a question -- not a comment on some other answer, an actual new question. That's the way this site works; the reason for that is so that in the future others could potentially benefit from your question and the answers that follow; if you were just answered in a comment, you would be helped but others would not benefit as a community.Bullshit

© 2022 - 2024 — McMap. All rights reserved.