Alex Rivera | Logout

Git pre-commit hook : changed/added files

Asked 2010-03-09T20:49:01.050
101

I am writing a pre-commit hook. I want to run php -l against all files with .php extension. However I am stuck.

I need to obtain a list of new/changed files that are staged. deleted files should be excluded.

I have tried using git diff and git ls-files, but I think I need a hand here.

Edit
Report

1 Answer

121

A slightly neater way of obtaining the same list is:

git diff --cached --name-only --diff-filter=ACMR

This will return the list of files that need to be checked by a pre-commit hook (A=Added, C=Copied, M=Modified, R=Renamed).

But just running php -l on your working copy may not be the right thing to do. If you are doing a partial commit i.e. just selecting a subset of the differences between your current working set and the HEAD for the commit, then the test will be run on your working set, but will be certifying a commit that has never existed on your disk.

To do it right you should extract the whole staged image to a temp area and perform the test there .

rm -rf $TEMPDIR
mkdir -p $TEMPDIR
git checkout-index --prefix=$TEMPDIR/ -af
git diff --cached --name-only --diff-filter=ACM | xargs -n 1 -I '{}' \bin\echo TEMPDIR/'{}' | grep \\.php | xargs -n 1 php -l

See Building a better pre-commit hook for Git for another implementation.

answered 2010-06-18T10:53:24.870

Your Answer