Git pre-commit hook: getting list of changed files

Mikko Ohtamaa picture Mikko Ohtamaa · Apr 15, 2012 · Viewed 9k times · Source

I am developing validation and linting utility to be integrated with various commit hooks, including Git one

https://github.com/miohtama/vvv

Currently validators and linters are run against the whole project codebase on every commit. However, it would be much more optimal to run them against changed files only. For this, I would need to know changed files list in my Git precommit hook (in Python)

https://github.com/miohtama/vvv/blob/master/vvv/hooks/git.py

What options I have to extract the changed files list (in Python if that matters)?

Answer

torek picture torek · Apr 15, 2012

The pre-commit hook is a bit of a pain, if you really want to make things work "right", because what's in the work tree is not necessarily the same as what is to be committed:

$ echo morestuff >> file1; echo morestuff >> file2
$ git add file1 # but not file2
$ git commit -m 'modified two files but check in just one'

You can use git diff-index --cached HEAD to get a list of "what's about to be checked-in". See also, e.g., http://newartisans.com/2009/02/building-a-better-pre-commit-hook-for-git/.