Skip to content

Instantly share code, notes, and snippets.

@gnovaro
Last active February 1, 2023 19:16
Show Gist options
  • Save gnovaro/4e195b2806316fa6f2da749118cbb0bd to your computer and use it in GitHub Desktop.
Save gnovaro/4e195b2806316fa6f2da749118cbb0bd to your computer and use it in GitHub Desktop.
pre-commit php check var_dump, print_r, die, dd and php syntax errors, include inside your .git/hooks folder
#!/bin/bash
# This script check for errors before commmit
#
# Add execute permissions first: chmod +x pre-commit
#
# Search for debug information inside .php files
# var_dump() , print_r(), die(), dd() y shortag
# If found any, stops the commit
# Put this file inside .git/hooks in your clone copy
# https://stackoverflow.com/questions/6879501/filter-git-diff-by-type-of-change
# @author: Gustavo Novaro
# @url: https://gist.github.com/gnovaro/4e195b2806316fa6f2da749118cbb0bd
# version: 2.2.0
VAR=$(git diff --cached --diff-filter=ACM | grep -w "var_dump")
if [ ! -z "$VAR" ]; then
printf "\n"
echo -e "\e[31m var_dump was found in file. commit canceled.\e[0m"
printf "\n"
exit 1
fi
VAR=$(git diff --cached --diff-filter=ACM | grep -w "<?=")
if [ ! -z "$VAR" ]; then
printf "\n"
echo -e "\e[31m php short tag <?= was found in file. commit canceled.\e[0m"
printf "\n"
exit 1
fi
VAR=$(git diff --cached --diff-filter=ACM | grep -w "print_r")
if [ ! -z "$VAR" ]; then
printf "\n"
echo -e "\e[31m print_r() was found in file. commit canceled.\e[0m"
printf "\n"
exit 1
fi
DD=$(git diff --cached --diff-filter=ACM | grep -w "dd(")
if [ ! -z "$DD" ]; then
printf "\n"
echo -e "\e[31m dd() was found in file. commit canceled.\e[0m"
printf "\n"
exit 1
fi
DIE=$(git diff --cached --diff-filter=ACM | grep -w "die(")
if [ ! -z "$DIE" ]; then
printf "\n"
echo -e "\e[31m die() was found in file. commit canceled.\e[0m"
printf "\n"
exit 1
fi
# PHP Syntax linter check
php_files=$(git status --short | grep -E '^(A|M)' | awk '{ print $2 }' | grep -E '\.php$')
for file in $php_files; do
php_out=$(php -l "$file")
if ! [ $? -eq 0 ]; then
echo "Syntax error with ${file}:"
echo "$php_out" | grep -E '^Parse error'
exit 1
fi
done
# Bash Syntax linter check
sh_files=$(git status --short | grep -E '^(A|M)' | awk '{ print $2 }' | grep -E '\.sh$')
for file in $sh_files; do
sh_out=$(bash -v "$file" 2>&1)
if ! [ $? -eq 0 ]; then
echo "Syntax error with ${file}:"
echo "$sh_out" | grep -E '^Parse error'
exit 1
fi
done
@cgsmith
Copy link

cgsmith commented Feb 1, 2023

This does not allow anything that is found in the file to be removed. as an example:
image

@gnovaro
Copy link
Author

gnovaro commented Feb 1, 2023

This does not allow anything that is found in the file to be removed. as an example: image

Usually you don't need to do a die also in this case... for example you can use exit https://www.php.net/manual/en/function.readfile.php

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment