views:

758

answers:

5

What I have so far is

#!/bin/sh

php_syntax_check()
{
    retval=0
    for i in $(git-diff-index --name-only --cached HEAD -- | grep -e '\.php$'); do
     if [ -f $i ]; then
      output=$(php -l $i)
      retval=$?
      if [ $retval -gt 0 ]; then
       echo "=============================================================================="
       echo "Unstaging $i for the commit due to the follow parse errors"
       echo "$output"
       git reset -q HEAD $i
      fi
     fi
    done

    if [ $retval -gt 0 ]; then
     exit $retval
    fi
}
php_syntax_check
A: 

Does this work? Is it a case of your code isn't doing what you need, or, does it have some limitations?

Andrew

Andrew Taylor
A: 

@Andrew Taylor This works ok but since it is the first git hook that I've written I was just wondering if there was a simpler or cleaner way to do it.

Rodney Amato
+2  A: 

I'm sorry if it's offtopic, but aren't you supposed to run some kind of automated tests (which would imply that the code has no syntax errors) before doing a commit?

Anonymous
A: 

If you've got the php5-cli installed you can write your pre-commit in PHP and use the syntax your more familiar with.

Just do something more like.

#!/usr/bin/php
<?php /* Your pre-commit check. */ ?>
A: 

If the commit is a partial commit (not all the changes in the working tree are committed), then this make give incorrect results since it tests the working copy and not the staged copy.

One way to do this could be:

git diff --cached --name-only --diff-filter=ACMR | xargs git checkout-index --prefix=$TMPDIR/ --
find $TMPDIR -name '*.php' -print | xargs -n 1 php -l

Which would make a copy of the staged images into a scratch space and then run the test command on them there. If any of the files include other files in the build then you may have to recreate the whole staged image in the test tree and then test the changed files there (See: Git pre-commit hook : changed/added files).

LarryH