Instantly share code, notes, and snippets.

Embed
What would you like to do?
a pre commit hook for PHP and JSON file
#!/bin/bash
PROJECT=`php -r "echo dirname(dirname(dirname(realpath('$0'))));"`
STAGED_PHP_FILES=`git diff --cached --name-only --diff-filter=ACMR HEAD | grep \\\\.php`
STAGED_JSON_FILES=`git diff --cached --name-only --diff-filter=ACMR HEAD | grep \\\\.json$`
# Determine if a file list is passed
if [ "$#" -eq 1 ]
then
oIFS=$IFS
IFS='
'
SFILES="$1"
IFS=$oIFS
fi
SFILES_PHP=${SFILES:-$STAGED_PHP_FILES}
SFILES_JSON=${SFILES:-$STAGED_JSON_FILES}
echo "Checking PHP Lint..."
for FILE in $SFILES_PHP
do
php -l -d display_errors=0 $PROJECT/$FILE
if [ $? != 0 ]
then
echo "Fix the error before commit. Aborting commit."
exit 1
fi
done
echo "Checking JSON syntax..."
for JSONFILE in $SFILES_JSON
do
JSONFILEWITHPATH=$PROJECT/$JSONFILE
JSONERROR=`php -r '$f=file_get_contents("'$JSONFILEWITHPATH'");$j=json_decode($f );$e=json_last_error();$m=json_last_error_msg();echo (empty($e)?"":$m.PHP_EOL);'`;
if [[ ! -z $JSONERROR ]]
then
echo "$JSONFILEWITHPATH has errors! Fix the error \"$JSONERROR\" before commit. Aborting commit."
exit 1
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment