Last active
November 25, 2022 18:44
-
-
Save serhiikamolov/65025cbb2a352d398e25281be1141835 to your computer and use it in GitHub Desktop.
Git pre-commit hook with phpcs, phpstan and phpunit
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
RED='\033[0;31m' | |
GREEN='\033[0;32m' | |
YELLOW='\033[1;33m' | |
NC='\033[0m' # No Color | |
echo -e "\n${GREEN}Running pre-commit hook${NC}" | |
# Get list of the modified files | |
phpfiles=$(git diff --name-only --diff-filter=d HEAD | grep \.php) | |
if [ "$phpfiles" != "" ]; then | |
echo -ne "PHP Code Sniffer..." | |
test=$(./vendor/bin/phpcs -q --report=diff $phpfiles) | |
if [ "$test" = "" ]; then | |
echo -e "${GREEN}OK${NC}" | |
else | |
echo -e "${RED}FAILED" | |
echo -e "${RED}\n$test${NC}" | |
echo -ne "\nTry to run"; | |
echo -e "\`${YELLOW}./vendor/bin/phpcbf $phpfiles${NC}\`" | tr '\n' ' ' | |
echo -e "\nto fix found errors automatically or use \`${YELLOW}./vendor/bin/phpcs${NC}\` to find out more details\n"; | |
exit 1; | |
fi | |
echo -ne "PHPStan analysis..." | |
# Run analyse in quiet mode | |
./vendor/bin/phpstan analyse -q $phpfiles --memory-limit=-1 | |
# $? stores exit value of the last command | |
if [ $? -ne 0 ]; then | |
echo -e "${RED}FAILED${NC}" | |
# Run analyse in debug mode to get the errors list | |
./vendor/bin/phpstan analyse $phpfiles --debug | |
echo -e "Run \`${YELLOW}./vendor/bin/phpstan analyse${NC}\` to find out more details\n"; | |
exit 1 | |
else | |
echo -e "${GREEN}OK${NC}" | |
fi | |
echo -ne "Running tests..." | |
output=`./vendor/bin/phpunit` | |
returnCode=$? | |
if [ $returnCode -ne 0 ]; then | |
echo -e "${RED}FAILED${NC}" | |
# find the line with the summary. | |
while read -r line; do | |
if [[ $line =~ Failures: ]] ; then | |
summary=$line | |
break | |
fi | |
done <<< "$output" | |
# output the status. | |
echo -e "${RED}$summary${NC}" | |
echo | |
echo -e "Run \`${YELLOW}./vendor/bin/phpunit${NC}\` to find out more details\n"; | |
exit 1 | |
else | |
echo -e "${GREEN}OK${NC}" | |
fi | |
echo -e "${GREEN}Proceeding with commit. Have a nice day.${NC}\n" | |
else | |
echo -e "${GREEN}Nothing to analyse${NC}\n" | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment