phpcs pre-commit git hook script
#!/bin/bash | |
# Pre-commit Git hook. | |
# Runs PHP CS on PHP files. | |
# Code slightly modified from the original | |
# https://github.com/BernardoSilva/git-hooks-php/blob/2149da8d4d9737c06137a825abfead11135840d3/pre-commit | |
# | |
# If you absolutely must commit without testing, | |
# use: git commit --no-verify | |
# This will check only staged files to be commited. | |
filenames=($(git diff --staged --name-only HEAD | grep -v Vendor)) | |
# This will set text to red in terminal. | |
text_red=`tput setaf 1` | |
# This will set the text to green in terminal. | |
text_green=`tput setaf 2` | |
# This will reset the terminal text to normal. | |
text_reset=`tput sgr0` | |
numberFilesChanged="${#filenames[@]}" | |
errorsFound=0 | |
# known php_codesniffer files where it looks for configuration in project root | |
phpcs_file=./phpcs.xml | |
phpcs_dist_file=./phpcs.xml.dist | |
# Use PSR2 standard as default only when no phpcs file is present in project root | |
if [[ ! -e "$phpcs_file" && ! -e "$phpcs_dist_file" ]]; then | |
default_standard=--standard=PSR2 | |
else | |
default_standard="" | |
fi | |
if [[ $numberFilesChanged > 0 ]]; | |
then | |
echo "$numberFilesChanged files were changed, running php-cs-fixer" | |
# Run throw changed files. | |
for i in "${filenames[@]}" | |
do | |
if [[ $i == *.php ]] && [ -f $i ]; | |
then | |
# Run PHP Code Beautifier and Fixer first. | |
./bin/phpcbf $default_standard -p $i | |
# Run PHP Code Style Check and detect in the fixer was not able to fix code. | |
./bin/phpcs $default_standard -p $i | |
checkResult=$? | |
if [ ${checkResult} -eq 0 ]; | |
then | |
# File had some issues. Now it is fine. Add this file to git again. | |
git add $i | |
else | |
((errorsFound++)) | |
fi | |
fi | |
done | |
fi | |
if [[ ${errorsFound} == 0 ]] | |
then | |
echo "${text_green}PHP Code Beautifier and Fixer finished execution successfully.${text_reset}" | |
exit 0; | |
else | |
echo "${text_red}Errors or warnings were found please fix them and commit again.${text_reset}" | |
exit 1; | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment