Skip to content

Instantly share code, notes, and snippets.

@ronanmccoy
Last active October 15, 2018 19:09
Show Gist options
  • Save ronanmccoy/6a19c4b47d8219f88faa0f274da5bef5 to your computer and use it in GitHub Desktop.
Save ronanmccoy/6a19c4b47d8219f88faa0f274da5bef5 to your computer and use it in GitHub Desktop.
Githook to check PHP syntax before committing changes.
/**
*
* ******* IMPORTANT *******
* This is not a valid composer.json, but
* only an example of what to add to the valid
* composer.json file in your project.
*
* The scripts here will run with 'composer install'
* or 'composer update' (though be aware that 'composer
* update' will update everything defined in the
* composer.json file) and only if there is a
* composer.lock file present. The first line will
* copy any files in bin/githooks to .git/hooks/,
* overwriting any matching files. The second line
* will make the 'pre-commit' file executable.
*
**/
{
.
.
.
.
"scripts": {
"post-install-cmd": [
"cp -Rf bin/githooks/. .git/hooks/",
"chmod +x .git/hooks/pre-commit"
]
}
.
.
.
.
}
#!/bin/sh
#
# Githook script to check PHP syntax using 'php -l' in changed files before
# committing. If the syntax check fails, the script will exit with a non-zero
# status which will halt the commit, printing a custom message along with
# the PHP syntax error.
#
# To use: copy the script to the path .git/hook/ with the name pre-commit,
# then modify the permissions to make the script executable.
#
# Alternatively this can be placed in a directory in the project
# (e.g. bin/githooks) so that is can be commited to a repo, and
# then use composer to copy the script to .git/hooks/
# and make the file executable (see next file in this gist).
#
status=0
for file in $(git status --porcelain | grep '.php' | awk '$1 != "D" { print $2; }'); do
msg=$(php -l $file);
if [ $? -gt 0 ]; then
printf '\e[5;32;41mPre-commit error found. Commit failed. You shall not pass!!\n\e[m '
status=1
echo $msg;
fi
done
exit $status
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment