SVN pre-commit hook script to check PHP syntax and CodeSniffer

SVN supports pre and post-commit hook scripts.

The former can be used to do some checks on the code before having it committed. In the example below, a hook script I use (on a dreamhost server of mine) to check if the committed files contain PHP syntax errors or the code doesn’t satisfy the code sniffer rules.

Pre-commit hook scripts
It returns a message error with details of PHP syntax or code sniffer errors. In case there is an error, the commit fails.
Paths to code sniffer, php, svnlook, awk, greo, sed have to be set depending on your machine. Code Sniffer and pear are installed locally as it’s a shared hosting.

#!/bin/sh

REPOS="$1"
TXN="$2"

# CODE SNIFFER
/home/[omit]/.pear/home/[omit]/pear/download/PHP_CodeSniffer-1.2.2/scripts/phpcs-svn-pre-commit --standard=Zend  "$REPOS" -t "$TXN" >&2 || exit 1

# PHP SNTAX CHECK

PHP="/usr/local/php5/bin/php"
SVNLOOK="/usr/bin/svnlook"
AWK="/usr/bin/awk"
GREP="/bin/egrep"
SED="/bin/sed"

CHANGED=`$SVNLOOK changed -t "$TXN" "$REPOS" | $GREP "^[U|A]" | $AWK '{print $2}' | $GREP .php$`

for FILE in $CHANGED
do
    MESSAGE=`$SVNLOOK cat -t "$TXN" "$REPOS" "$FILE" | $PHP -l`
    if [ $? -ne 0 ]
    then
        echo 1>&2
        echo "***********************************" 1>&2
        echo "PHP error in: $FILE:" 1>&2
        echo `echo "$MESSAGE" | $SED "s| -| $FILE|g"` 1>&2
        echo "***********************************" 1>&2
        exit 1
    fi

done

One thought on “SVN pre-commit hook script to check PHP syntax and CodeSniffer

  1. Almost exactly what i was trawling for, helped me a lot understanding what i needed. thank you 🙂

Comments are closed.