Skip to content

Instantly share code, notes, and snippets.

@kumarldh
Created September 6, 2017 06:38
Show Gist options
  • Save kumarldh/77e2dda38ea2d0a54c90521f1cf0c7fc to your computer and use it in GitHub Desktop.
Save kumarldh/77e2dda38ea2d0a54c90521f1cf0c7fc to your computer and use it in GitHub Desktop.
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