Skip to content

Instantly share code, notes, and snippets.

@cillosis
Created August 28, 2013 20:27
Show Gist options
  • Save cillosis/6370801 to your computer and use it in GitHub Desktop.
Save cillosis/6370801 to your computer and use it in GitHub Desktop.
Git Hook - PHP Syntax Checker (pre-commit)
echo ""
echo "******************************"
echo "** Running PHP Syntax Check **"
echo "******************************"
if [ -z "$PHP_BIN" ]
then
PHP_BIN=php
fi
if [ "$(echo -e test)" = test ]
then
echo_e="echo -e"
else
echo_e="echo"
fi
# necessary check for initial commit
if git rev-parse --verify HEAD >/dev/null 2>&1
then
against=HEAD
else
# Initial commit: diff against an empty tree object
against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
fi
errors=""
if ! which "$PHP_BIN" >/dev/null 2>&1
then
echo "PHP Syntax check failed:"
echo "PHP binary does not exist or is not in path: $PHP_BIN"
exit 1
fi
# dash does not support $'\n':
# http://forum.soft32.com/linux2/Bug-409179-DASH-Settings-IFS-work-properly-ftopict70039.html
IFS='
'
# get a list of staged files
for line in $(git diff-index --cached --full-index $against)
do
# split needed values
sha=$(echo $line | cut -d' ' -f4)
temp=$(echo $line | cut -d' ' -f5)
status=$(echo $temp | cut -d' ' -f1)
filename=$(echo $temp | cut -d' ' -f2)
# file extension
ext=$(echo $filename | sed 's/^.*\.//')
# only check files with php extension
if [ $ext != "php" ]
then
continue
fi
# do not check deleted files
if [ $status = "D" ]
then
continue
fi
# check the staged file content for syntax errors
# using php -l (lint)
result=$(git cat-file -p $sha | "$PHP_BIN" -n -l -ddisplay_errors\=1 -derror_reporting\=E_ALL -dlog_errrors\=0 2>&1)
if [ $? -ne 0 ]
then
# Swap back in correct filenames
errors=$(echo "$errors"; echo "$result" | grep ':' | sed -e "s@in - on@in $filename on@g")
fi
done
unset IFS
if [ -n "$errors" ]
then
echo "!! PHP Syntax check failed !!"
$echo_e "$errors"
echo ""
exit 1
fi
echo "Syntax Check Completed!"
echo ""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment