Search code examples
pythongitgitpython

How to get list of staged files for commit ? (fullpaths)


I'm trying to get the list of files staged for the next commit. I want their fullpath based on the repository's base directory.

How do I do that in python, with or even better, without the gitpython module ?

I have a starter :

repo = git.Repo()
staged_files = repo.index.diff("HEAD")

but I can't access their path.


Solution

  • Ok I found 2 ways of doing it :

    Using gitpython :

    repo = git.Repo()
    staged_files = repo.index.diff("HEAD")
    for x in staged_files:
        print(x.a_path) # Here we can use a_path or b_path, I do not know the difference...
    

    Without gitpython :

    import subprocess
    subprocess.getoutput(['git diff --name-only --cached'])
    

    And even better :

    import subprocess
    proc = subprocess.Popen(['git', 'diff', '--name-only', '--cached'], stdout=subprocess.PIPE)
    staged_files = proc.stdout.readlines()
    staged_files = [f.decode('utf-8') for f in staged_files]
    staged_files = [f.strip() for f in staged_files]
    print(staged_files)