Skip to content

Instantly share code, notes, and snippets.

@raank
Last active September 2, 2021 21:33
Show Gist options
  • Save raank/d4ab4baed4c233a100d3698e14898d4c to your computer and use it in GitHub Desktop.
Save raank/d4ab4baed4c233a100d3698e14898d4c to your computer and use it in GitHub Desktop.
Instalador do Pre-Commit
#!/bin/bash
##########
# PHP STAN
##########
curl -OL https://github.com/phpstan/phpstan/releases/download/0.12.98/phpstan.phar
sudo chmod a+x phpstan.phar
sudo mv phpstan.phar /usr/local/bin/phpstan
##########
# PHP MD
##########
curl -OL https://phpmd.org/static/latest/phpmd.phar
sudo chmod a+x phpmd.phar
sudo mv phpmd.phar /usr/local/bin/phpmd
##########
# PHP CS
##########
curl -OL https://squizlabs.github.io/PHP_CodeSniffer/phpcs.phar
sudo chmod a+x phpcs.phar
sudo mv phpcs.phar /usr/local/bin/phpcs
##########
# PHP CBF
##########
curl -OL https://squizlabs.github.io/PHP_CodeSniffer/phpcbf.phar
sudo chmod a+x phpcbf.phar
sudo mv phpcbf.phar /usr/local/bin/phpcbf
##########
# PHP CPD
##########
curl -OL https://phar.phpunit.de/phpcpd.phar
sudo chmod a+x phpcpd.phar
sudo mv phpcpd.phar /usr/local/bin/phpcpd
# Baixando arquivo para pre-commit
curl -O https://gist.githubusercontent.com/raank/d4ab4baed4c233a100d3698e14898d4c/raw/44c407be4d8d302e229d28b4cd48318bbdca3076/pre-commit
# Criando pasta de Hooks caso não exista
if ! [ -d "./.git/hooks" ]; then
sudo mkdir .git/hooks
fi
# Movendo arquivo de pre-commit para a pasta hooks
sudo mv pre-commit .git/hooks/pre-commit
# Permissões do arquivo.
sudo chmod +x .git/hooks/pre-commit
echo "Arquivo de Pré-Commit configurado com sucesso!"
#!/usr/bin/env bash
##########
# Git Pre-Commit file for PHP projects.
###
#
# This hook performs the following validation:
# - PHP Lint (http://php.net/manual/en/features.commandline.options.php)
# - PHP CodeSniffer (PHPCS + (PHPCBF) (https://github.com/squizlabs/PHP_CodeSniffer)
# - PHP Coding Standards Fixer (PHP CS Fixer) (https://github.com/FriendsOfPHP/PHP-CS-Fixer)
# - PHP Mess Detector (PHPMD) (https://phpmd.org/)
# - PHP Copy/Paste Detector (PHPCPD) (https://github.com/sebastianbergmann/phpcpd)
# - PHP Stan
#
# @version 1.0.0
# @author Felipe Rank <[email protected]>
##########
if git rev-parse --verify HEAD >/dev/null 2>&1
then
against=HEAD
else
# Initial commit: diff against an empty tree object
against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
fi
# If you want to allow non-ASCII filenames set this variable to true.
allownonascii=$(git config --bool hooks.allownonascii)
# Redirect output to stderr.
exec 1>&2
# Cross platform projects tend to avoid non-ASCII filenames; prevent
# them from being added to the repository. We exploit the fact that the
# printable range starts at the space character and ends with tilde.
if [ "$allownonascii" != "true" ] &&
# Note that the use of brackets around a tr range is ok here, (it's
# even required, for portability to Solaris 10's /usr/bin/tr), since
# the square bracket bytes happen to fall in the designated range.
test $(git diff --cached --name-only --diff-filter=A -z $against |
LC_ALL=C tr -d '[ -~]\0' | wc -c) != 0
then
cat <<\EOF
Error: Attempt to add a non-ASCII file name.
This can cause problems if you want to work with people on other platforms.
To be portable it is advisable to rename the file.
If you know what you are doing you can disable this check using:
git config hooks.allownonascii true
EOF
exit 1
fi
# If there are whitespace errors, print the offending file names and fail.
# exec git diff-index --check --cached $against --
#################
# Terminal Colors
#################
###
# Regular
###
color_regular_black='\033[0;30m'
color_regular_red='\033[0;31m'
color_regular_green='\033[0;32m'
color_regular_yellow='\033[0;33m'
color_regular_blue='\033[0;34m'
color_regular_purple='\033[0;35m'
color_regular_cyan='\033[0;36m'
color_regular_white='\033[0;37m'
###
# Bold
###
color_bold_black='\033[1;30m'
color_bold_red='\033[1;31m'
color_bold_green='\033[1;32m'
color_bold_yellow='\033[1;33m'
color_bold_blue='\033[1;34m'
color_bold_purple='\033[1;35m'
color_bold_cyan='\033[1;36m'
color_bold_white='\033[1;37m'
###
# Underline
###
color_underline_black='\033[4;30m'
color_underline_red='\033[4;31m'
color_underline_green='\033[4;32m'
color_underline_yellow='\033[4;33m'
color_underline_blue='\033[4;34m'
color_underline_purple='\033[4;35m'
color_underline_cyan='\033[4;36m'
color_underline_white='\033[4;37m'
###
# Background
###
color_background_black='\033[40m'
color_background_red='\033[41m'
color_background_green='\033[42m'
color_background_yellow='\033[43m'
color_background_blue='\033[44m'
color_background_purple='\033[45m'
color_background_cyan='\033[46m'
color_background_white='\033[47m'
color_reset='\033[0m'
###########
# Functions
###########
function message_failure() {
printf "${color_bold_red}🤦 $1 ${color_reset}\n"
}
function message_success() {
printf "${color_bold_green}$1 🍺${color_reset}\n"
}
function message_warning() {
printf "${color_bold_yellow}⚠️ $1 ${color_reset}\n"
}
function message_info() {
printf "${color_bold_blue}☝️️ $1 ${color_reset}\n"
}
# Message welcome
echo "${color_bold_cyan}"
cat <<\EOF
________ ___ ___ ________ ________ ________
|\ __ \ |\ \|\ \ |\ __ \ |\ __ \ |\ __ \
\ \ \|\ \ \ \ \\\ \ \ \ \|\ \ \ \ \|\ \ \ \ \|\ \
\ \ ____\ \ \ __ \ \ \ ____\ \ \ \\\ \ \ \ __ \
\ \ \___| \ \ \ \ \ \ \ \___| \ \ \\\ \ \ \ \ \ \
\ \__\ \ \__\ \__\ \ \__\ \ \_____ \ \ \__\ \__\
\|__| \|__|\|__| \|__| \|___| \__\ \|__|\|__|
\|__|
EOF
echo
echo "${color_reset}#"
echo "# ${color_bold_red}Programe com consciência, para o usuário!${color_reset}"
echo "# Padrões de códigos definidos pelo time de ${color_bold_white}TECH${color_reset}!"
echo "#"
######################
# Checking PHP Project
######################
# Exit 0 if no errors found
# Exit 1 if errors were found
# Create empty errors array.
declare -a errors
# Fetch all changed php files and validate them.
# This will check only staged files to be commited.
files=$(git diff --cached --name-only --diff-filter=ACM $against | grep '\.php$' | grep -Ev '\.(blade.php|txt)$' | grep -Ev '(_ide_helper.php)$')
# Project Folder.
project=$(git rev-parse --show-toplevel)
# Apenas caminhos e nomes dos arquivos: /path/file.php,/foo/file.php,/bar/file.php
for relative_file_path in $files
do
staged_files="$staged_files $(git rev-parse --show-toplevel)/$relative_file_path"
# file_name=$(basename "$relative_file_path")
# file_entension=${file_name##*.}
done
# Replace first blank only
staged_files=${staged_files/ /''}
# Separated by spaces
staged_files_separated_by_spaces=$staged_files
# Remove blank spaces with comma
# Separated by commas and spaces
staged_files_separated_by_comma=${staged_files// /,}
staged_files_separated_by_space=${staged_files// / }
if [ -n "$files" ]; then
CURRENT_DIR=$(PWD)
echo "\n\n-------------------------------------------"
echo "- ${color_bold_cyan}PHP Lint${color_reset}"
echo "-------------------------------------------\n"
# Check for errors when running PHP LINT.
php_lint_errors=false
for file in $files; do
# Check if they are valid php files.
php_lint_output=`php -l -d display_errors=On $file 2>&1 | grep 'PHP Parse error:'`
# If it did contain errors, we have output.
if [ -n "$php_lint_output" ]; then
# Printing error message.
message_failure "$php_lint_output"
# Adding error message.
errors=("${errors[@]}" "$php_lint_output")
php_lint_errors=true
fi
done
if [ "$php_lint_errors" = false ]; then
message_success '✔ Etapa sem erros!'
else
exit 1
fi
echo "\n\n-------------------------------------------"
echo "- ${color_bold_cyan}PHP CodeSniffer + PHP Code Beautifier${color_reset}"
echo "-------------------------------------------\n"
# PHP CodeSniffer default execution file.
#
# curl -OL https://squizlabs.github.io/PHP_CodeSniffer/phpcs.phar
phpcs_local_bin="/usr/local/bin/phpcs"
# Default command to run PHP CodeSniffer.
phpcs_bin="php $phpcs_local_bin"
# Default command via install local project package with Composer (Depot Manager for PHP).
phpcs_vendor_bin="vendor/bin/phpcs"
# Standard command via composer global installation.
phpcs_global_bin="/usr/local/bin/phpcs"
# Verifying command default based on existing conditions.
if [ -f "$phpcs_vendor_bin" ]; then
phpcs_bin=$phpcs_vendor_bin
else
if hash phpcs 2>/dev/null; then
phpcs_bin=$phpcs_global_bin
else
if [ -f "$phpcs_local_exec" ]; then
phpcs_bin=$phpcs_bin
else
message_warning "Executável do PHP Codesniffer não foi encontrado em $phpcs_vendor_bin, $phpcs_global_bin ou $phpcs_local_exec"
exit 1
fi
fi
fi
if ! hash phpcbf 2>/dev/null; then
message_warning "PHP Code Beautifier não foi encontrado!"
message_info "Visite: https://github.com/squizlabs/PHP_CodeSniffer/wiki/Fixing-Errors-Automatically"
exit 1
fi
# Arguments both for use for PHPCS and for PHPCBF.
php_cs_cbf_common_arguments="--standard=PSR12 --colors --error-severity=1 --ignore='*blade.php*,*twig.php*' --tab-width=4 --encoding=utf-8 --extensions=php -d --memory_limit=32M -n"
# Only PHPCS exclusives arguments.
phpcs_arguments="-s --report=full --report-width=auto"
# Check for errors when running PHPCS.
phpcs_errors=false
#printf "${color_bold_black}${color_background_yellow}PHP CodeSniffer Arguments${color_reset} ${color_bold_yellow}${php_cs_cbf_common_arguments} ${phpcs_arguments}${color_reset}\n"
#printf "${color_bold_black}${color_background_yellow}Use PHPCBF To Fix Problems${color_reset} ${color_bold_green}phpcbf${color_reset}${color_bold_yellow} ${color_bold_purple}{FILES OR FOLDER}${color_bold_yellow} ${php_cs_cbf_common_arguments}\n"
for file in $files; do
GET_FILE="${CURRENT_DIR}/${file}"
# Error codes before applying PHPCBF.
phpcs_codestyle_errors_before_autofix=$($phpcs_bin $GET_FILE $php_cs_cbf_common_arguments $phpcs_arguments)
# ([-z]=Empty)
if [ -z "$phpcs_codestyle_errors_before_autofix" ];
then
# No errors to fix, skip to next file.
continue
fi
# Run PHP Code Beautifier and Fixer the file.
# Begin PHP Code Beautifier and Fixer.
phpcbf_output="$(phpcbf $GET_FILE $php_cs_cbf_common_arguments)"
if [ -n "$phpcbf_output" ]; then
# File had some issues but they were automatically fixed.
printf "${color_bold_green}Erros de estilo de código foram alterados! Refaça o commit.${color_reset}\n"
# Display PHPCBF filtered output.
printf "${phpcbf_output}\n"
fi
# Run PHP Code Style Check and detect in the fixer was not able to fix code.
phpcs_codestyle_errors="$($phpcs_bin $GET_FILE $php_cs_cbf_common_arguments $phpcs_arguments)"
# If it did contain errors, we have output.
# Check last command (PHPCS) code for fail.
# ([-n]=Not Empty)
if [ -n "$phpcs_codestyle_errors" ]; then
# Display error and PHPCS filtered output.
# Display processing file error.
printf "${phpcs_codestyle_errors}\n"
# Adding error message.
errors=("${errors[@]}" "$output")
phpcs_errors=true
fi
done
if [ "$phpcs_errors" = false ]; then
message_success '✔ Etapa sem erros!'
fi
echo "\n\n-------------------------------------------"
echo "- ${color_bold_cyan}PHP Coding Standards Fixer (PSR12) ${color_reset}"
echo "-------------------------------------------\n"
#message_info "Running PHP Code Sniffer..."
# Verificando se arquivo binário executável existe para [php-cs-fixer].
if ! hash php-cs-fixer 2>/dev/null; then
message_warning "PHP Coding Standards Fixer não instalado"
message_info "Visite: https://github.com/FriendsOfPHP/PHP-CS-Fixer#installation"
exit 1
fi
printf "${color_bold_white}✔︎ Regras: ${color_bold_yellow}PSR12, Symfony${color_reset}\n"
printf "${color_bold_white}✔︎ Formato de Output: ${color_bold_yellow}Text (default)${color_reset}\n"
echo
git status --porcelain | grep -e '^[AM]\(.*\).php$' | cut -c 3- | while read line; do
# php-cs-fixer CHECK.
# --dry-run (The --dry-run option displays the files that need to be fixed but without actually modifying them).
php_cs_fixer_codestyle_dry_run=`php-cs-fixer --dry-run --diff --verbose --using-cache=no --rules=@PSR12,@Symfony fix ${line} 2>&1 | grep "diff"`
# Check last command (PHP-CS-FIXER) code for fixed.
if [ -n "$php_cs_fixer_codestyle_dry_run" ]; then
# Applicando PSRs e @Symfony.
php_cs_fixer_codestyle=`php-cs-fixer --diff --using-cache=yes --rules=@PSR12,@Symfony fix ${line} &>/dev/null`
git add ${line}
message_info "GIT ADD + PHP Coding Standards Fixer fixing: [ ${line} ]"
else
printf "${color_bold_green}✔ ${color_bold_white}${color_underline_white}${line}${color_reset}\n"
fi
done
echo "\n\n-------------------------------------------"
echo "- ${color_bold_cyan}PHPMD - PHP Mess Detector${color_reset}"
echo "-------------------------------------------\n"
if ! hash phpmd 2>/dev/null; then
message_warning "PHP Mess Detector não foi encontrado!"
message_info "Visit: https://phpmd.org/download/index.html"
exit 1
fi
# @see https://phpmd.org/rules/index.html
phpmd_rules="cleancode,codesize,controversial,design,naming,unusedcode"
printf "✔︎ Formato de Output: ${color_bold_yellow}text${color_reset}\n"
printf "✔︎ Regras: ${color_bold_yellow}${phpmd_rules}${color_reset}\n"
printf "✔︎ Extensão: ${color_bold_yellow}php${color_reset}\n\n"
#message_info "PHPMD - PHP Mess Detector: [ ${staged_files_separated_by_comma} ]"
# PHPMD running script
phpmd_output=$(phpmd ${staged_files_separated_by_comma} text "${phpmd_rules}" --suffixes php)
phpmd_retval=$?
if [ $phpmd_retval -ne 0 ]; then
message_failure "PHPMD - PHP Mess Detector detectou erros, resolva-os e volte a comitar."
echo
printf "${phpmd_output}\n"
# Adding error message.
errors=("${errors[@]}" "$phpmd_output")
else
message_success '✔ Etapa sem erros!'
fi
echo "\n\n-------------------------------------------"
echo "- ${color_bold_cyan}PHPStan - PHP Static Analyses${color_reset}"
echo "-------------------------------------------\n"
if ! hash phpstan 2>/dev/null; then
message_warning "PHP Stan Analyses não foi encontrado!"
message_info "Visite: https://phpstan.org/user-guide/getting-started#installation"
exit 1
fi
# PHPSTAN running script
phpstan_output=$(phpstan analyse ${staged_files_separated_by_space} --level=8 -a "${CURRENT_DIR}/vendor/autoload.php" -c "${CURRENT_DIR}/phpstan.neon" --memory-limit=-1)
phpstan_retval=$?
if [ $phpstan_retval -ne 0 ]; then
message_failure "PHPSTAN - PHP Stan Encontrou alguns erros. Resolva e volte a comitar."
printf "${phpstan_output}\n"
# Adding error message.
errors=("${errors[@]}" "$phpstan_output")
else
message_success '✔ Etapa sem erros!'
fi
echo "\n\n-------------------------------------------"
echo "- ${color_bold_cyan}PHP Copy/Paste Detector (PHPCPD)${color_reset}"
echo "-------------------------------------------\n"
if ! hash phpcpd 2>/dev/null; then
message_warning "PHP Copy/Paste Detector não foi encontrado!"
printf "${color_bold_white}Por favor instale o pacote: phpcpd, e.g.:${color_reset}\n"
exit 1
fi
phpcpd_arguments="--no-interaction --progress --min-lines=3 --min-tokens=40"
# PHPCPD running script
phpcpd_tmp=/tmp/t$$
phpcpd ${phpcpd_arguments} ${staged_files_separated_by_spaces} > $phpcpd_tmp
if grep -q 'Found' $phpcpd_tmp
then
message_failure "PHPCPD - PHP Copy/Paste Detector encontrou erros, resolva-os e volte a comitar!"
phpcpd_output="`cat $phpcpd_tmp`"
printf "${phpcpd_output}\n"
# Adding error message.
errors=("${errors[@]}" "$phpcpd_output")
else
message_success "✔ Sem erros - PHPCPD!"
fi
# Cleanup
rm /tmp/*.$$ 2>/dev/null
rm /tmp/*$$.txt 2>/dev/null
rm -f $phpcpd_tmp
fi
# If we have errors, exit with 1
if [ -n "$errors" ]; then
message_failure 'Por favor corrija os erros e volte a fazer o commit!'
exit 1
fi
echo "\n\n-------------------------------------------"
echo "- ${color_bold_green}Nenhum erro encontrado! 👏 👏 👏 👏${color_reset}"
echo "-------------------------------------------\n"
exit 0
#!/usr/bin/env bash
##########
# Git Pre-Commit file for PHP projects.
###
#
# This hook performs the following validation:
# - PHP Lint (http://php.net/manual/en/features.commandline.options.php)
# - PHP CodeSniffer (PHPCS + (PHPCBF) (https://github.com/squizlabs/PHP_CodeSniffer)
# - PHP Coding Standards Fixer (PHP CS Fixer) (https://github.com/FriendsOfPHP/PHP-CS-Fixer)
# - PHP Mess Detector (PHPMD) (https://phpmd.org/)
# - PHP Copy/Paste Detector (PHPCPD) (https://github.com/sebastianbergmann/phpcpd)
# - PHP Stan
#
# @version 1.0.0
# @author Felipe Rank <[email protected]>
##########
if git rev-parse --verify HEAD >/dev/null 2>&1
then
against=HEAD
else
# Initial commit: diff against an empty tree object
against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
fi
# If you want to allow non-ASCII filenames set this variable to true.
allownonascii=$(git config --bool hooks.allownonascii)
# Redirect output to stderr.
exec 1>&2
# Cross platform projects tend to avoid non-ASCII filenames; prevent
# them from being added to the repository. We exploit the fact that the
# printable range starts at the space character and ends with tilde.
if [ "$allownonascii" != "true" ] &&
# Note that the use of brackets around a tr range is ok here, (it's
# even required, for portability to Solaris 10's /usr/bin/tr), since
# the square bracket bytes happen to fall in the designated range.
test $(git diff --cached --name-only --diff-filter=A -z $against |
LC_ALL=C tr -d '[ -~]\0' | wc -c) != 0
then
cat <<\EOF
Error: Attempt to add a non-ASCII file name.
This can cause problems if you want to work with people on other platforms.
To be portable it is advisable to rename the file.
If you know what you are doing you can disable this check using:
git config hooks.allownonascii true
EOF
exit 1
fi
# If there are whitespace errors, print the offending file names and fail.
# exec git diff-index --check --cached $against --
#################
# Terminal Colors
#################
###
# Regular
###
color_regular_black='\033[0;30m'
color_regular_red='\033[0;31m'
color_regular_green='\033[0;32m'
color_regular_yellow='\033[0;33m'
color_regular_blue='\033[0;34m'
color_regular_purple='\033[0;35m'
color_regular_cyan='\033[0;36m'
color_regular_white='\033[0;37m'
###
# Bold
###
color_bold_black='\033[1;30m'
color_bold_red='\033[1;31m'
color_bold_green='\033[1;32m'
color_bold_yellow='\033[1;33m'
color_bold_blue='\033[1;34m'
color_bold_purple='\033[1;35m'
color_bold_cyan='\033[1;36m'
color_bold_white='\033[1;37m'
###
# Underline
###
color_underline_black='\033[4;30m'
color_underline_red='\033[4;31m'
color_underline_green='\033[4;32m'
color_underline_yellow='\033[4;33m'
color_underline_blue='\033[4;34m'
color_underline_purple='\033[4;35m'
color_underline_cyan='\033[4;36m'
color_underline_white='\033[4;37m'
###
# Background
###
color_background_black='\033[40m'
color_background_red='\033[41m'
color_background_green='\033[42m'
color_background_yellow='\033[43m'
color_background_blue='\033[44m'
color_background_purple='\033[45m'
color_background_cyan='\033[46m'
color_background_white='\033[47m'
color_reset='\033[0m'
###########
# Functions
###########
function message_failure() {
printf "${color_bold_red}🤦 $1 ${color_reset}\n"
}
function message_success() {
printf "${color_bold_green}$1 🍺${color_reset}\n"
}
function message_warning() {
printf "${color_bold_yellow}⚠️ $1 ${color_reset}\n"
}
function message_info() {
printf "${color_bold_blue}☝️️ $1 ${color_reset}\n"
}
# Message welcome
echo "${color_bold_cyan}"
cat <<\EOF
__ __ ______ __ __ ______ _____
/\ "-./ \ /\ ___\ /\ "-./ \ /\ ___\ /\ __-.
\ \ \-./\ \ \ \ __\ \ \ \-./\ \ \ \ __\ \ \ \/\ \
\ \_\ \ \_\ \ \_____\ \ \_\ \ \_\ \ \_____\ \ \____-
\/_/ \/_/ \/_____/ \/_/ \/_/ \/_____/ \/____/
EOF
echo
echo "${color_reset}#"
echo "# ${color_bold_red}Programe com consciência, para o usuário!${color_reset}"
echo "# Padrões de códigos definidos pelo time de ${color_bold_white}TECH${color_reset}!"
echo "#"
######################
# Checking PHP Project
######################
# Exit 0 if no errors found
# Exit 1 if errors were found
# Create empty errors array.
declare -a errors
# Fetch all changed php files and validate them.
# This will check only staged files to be commited.
files=$(git diff --cached --name-only --diff-filter=ACM $against | grep '\.php$' | grep -Ev '\.(blade.php|txt)$' | grep -Ev '(_ide_helper.php)$')
# Project Folder.
project=$(git rev-parse --show-toplevel)
# Apenas caminhos e nomes dos arquivos: /path/file.php,/foo/file.php,/bar/file.php
for relative_file_path in $files
do
staged_files="$staged_files $(git rev-parse --show-toplevel)/$relative_file_path"
# file_name=$(basename "$relative_file_path")
# file_entension=${file_name##*.}
done
# Replace first blank only
staged_files=${staged_files/ /''}
# Separated by spaces
staged_files_separated_by_spaces=$staged_files
# Remove blank spaces with comma
# Separated by commas and spaces
staged_files_separated_by_comma=${staged_files// /,}
staged_files_separated_by_space=${staged_files// / }
if [ -n "$files" ]; then
CURRENT_DIR=$(PWD)
echo "\n\n-------------------------------------------"
echo "- ${color_bold_cyan}PHP Lint${color_reset}"
echo "-------------------------------------------\n"
# Check for errors when running PHP LINT.
php_lint_errors=false
for file in $files; do
# Check if they are valid php files.
php_lint_output=`php -l -d display_errors=On $file 2>&1 | grep 'PHP Parse error:'`
# If it did contain errors, we have output.
if [ -n "$php_lint_output" ]; then
# Printing error message.
message_failure "$php_lint_output"
# Adding error message.
errors=("${errors[@]}" "$php_lint_output")
php_lint_errors=true
fi
done
if [ "$php_lint_errors" = false ]; then
message_success '✔ Etapa sem erros!'
else
exit 1
fi
echo "\n\n-------------------------------------------"
echo "- ${color_bold_cyan}PHP CodeSniffer + PHP Code Beautifier${color_reset}"
echo "-------------------------------------------\n"
# PHP CodeSniffer default execution file.
#
# curl -OL https://squizlabs.github.io/PHP_CodeSniffer/phpcs.phar
phpcs_local_bin="/usr/local/bin/phpcs"
# Default command to run PHP CodeSniffer.
phpcs_bin="php $phpcs_local_bin"
# Default command via install local project package with Composer (Depot Manager for PHP).
phpcs_vendor_bin="vendor/bin/phpcs"
# Standard command via composer global installation.
phpcs_global_bin="/usr/local/bin/phpcs"
# Verifying command default based on existing conditions.
if [ -f "$phpcs_vendor_bin" ]; then
phpcs_bin=$phpcs_vendor_bin
else
if hash phpcs 2>/dev/null; then
phpcs_bin=$phpcs_global_bin
else
if [ -f "$phpcs_local_exec" ]; then
phpcs_bin=$phpcs_bin
else
message_warning "Executável do PHP Codesniffer não foi encontrado em $phpcs_vendor_bin, $phpcs_global_bin ou $phpcs_local_exec"
exit 1
fi
fi
fi
if ! hash phpcbf 2>/dev/null; then
message_warning "PHP Code Beautifier não foi encontrado!"
message_info "Visite: https://github.com/squizlabs/PHP_CodeSniffer/wiki/Fixing-Errors-Automatically"
exit 1
fi
# Arguments both for use for PHPCS and for PHPCBF.
php_cs_cbf_common_arguments="--standard=PSR12 --colors --error-severity=1 --ignore='*blade.php*,*twig.php*' --tab-width=4 --encoding=utf-8 --extensions=php -d --memory_limit=32M -n"
# Only PHPCS exclusives arguments.
phpcs_arguments="-s --report=full --report-width=auto"
# Check for errors when running PHPCS.
phpcs_errors=false
#printf "${color_bold_black}${color_background_yellow}PHP CodeSniffer Arguments${color_reset} ${color_bold_yellow}${php_cs_cbf_common_arguments} ${phpcs_arguments}${color_reset}\n"
#printf "${color_bold_black}${color_background_yellow}Use PHPCBF To Fix Problems${color_reset} ${color_bold_green}phpcbf${color_reset}${color_bold_yellow} ${color_bold_purple}{FILES OR FOLDER}${color_bold_yellow} ${php_cs_cbf_common_arguments}\n"
for file in $files; do
GET_FILE="${CURRENT_DIR}/${file}"
# Error codes before applying PHPCBF.
phpcs_codestyle_errors_before_autofix=$($phpcs_bin $GET_FILE $php_cs_cbf_common_arguments $phpcs_arguments)
# ([-z]=Empty)
if [ -z "$phpcs_codestyle_errors_before_autofix" ];
then
# No errors to fix, skip to next file.
continue
fi
# Run PHP Code Beautifier and Fixer the file.
# Begin PHP Code Beautifier and Fixer.
phpcbf_output="$(phpcbf $GET_FILE $php_cs_cbf_common_arguments)"
if [ -n "$phpcbf_output" ]; then
# File had some issues but they were automatically fixed.
printf "${color_bold_green}Erros de estilo de código foram alterados! Refaça o commit.${color_reset}\n"
# Display PHPCBF filtered output.
printf "${phpcbf_output}\n"
fi
# Run PHP Code Style Check and detect in the fixer was not able to fix code.
phpcs_codestyle_errors="$($phpcs_bin $GET_FILE $php_cs_cbf_common_arguments $phpcs_arguments)"
# If it did contain errors, we have output.
# Check last command (PHPCS) code for fail.
# ([-n]=Not Empty)
if [ -n "$phpcs_codestyle_errors" ]; then
# Display error and PHPCS filtered output.
# Display processing file error.
printf "${phpcs_codestyle_errors}\n"
# Adding error message.
errors=("${errors[@]}" "$output")
phpcs_errors=true
fi
done
if [ "$phpcs_errors" = false ]; then
message_success '✔ Etapa sem erros!'
fi
echo "\n\n-------------------------------------------"
echo "- ${color_bold_cyan}PHP Coding Standards Fixer (PSR12) ${color_reset}"
echo "-------------------------------------------\n"
#message_info "Running PHP Code Sniffer..."
# Verificando se arquivo binário executável existe para [php-cs-fixer].
if ! hash php-cs-fixer 2>/dev/null; then
message_warning "PHP Coding Standards Fixer não instalado"
message_info "Visite: https://github.com/FriendsOfPHP/PHP-CS-Fixer#installation"
exit 1
fi
printf "${color_bold_white}✔︎ Regras: ${color_bold_yellow}PSR12, Symfony${color_reset}\n"
printf "${color_bold_white}✔︎ Formato de Output: ${color_bold_yellow}Text (default)${color_reset}\n"
echo
git status --porcelain | grep -e '^[AM]\(.*\).php$' | cut -c 3- | while read line; do
# php-cs-fixer CHECK.
# --dry-run (The --dry-run option displays the files that need to be fixed but without actually modifying them).
php_cs_fixer_codestyle_dry_run=`php-cs-fixer --dry-run --diff --verbose --using-cache=no --rules=@PSR12,@Symfony fix ${line} 2>&1 | grep "diff"`
# Check last command (PHP-CS-FIXER) code for fixed.
if [ -n "$php_cs_fixer_codestyle_dry_run" ]; then
# Applicando PSRs e @Symfony.
php_cs_fixer_codestyle=`php-cs-fixer --diff --using-cache=yes --rules=@PSR12,@Symfony fix ${line} &>/dev/null`
git add ${line}
message_info "GIT ADD + PHP Coding Standards Fixer fixing: [ ${line} ]"
else
printf "${color_bold_green}✔ ${color_bold_white}${color_underline_white}${line}${color_reset}\n"
fi
done
echo "\n\n-------------------------------------------"
echo "- ${color_bold_cyan}PHPMD - PHP Mess Detector${color_reset}"
echo "-------------------------------------------\n"
if ! hash phpmd 2>/dev/null; then
message_warning "PHP Mess Detector não foi encontrado!"
message_info "Visit: https://phpmd.org/download/index.html"
exit 1
fi
# @see https://phpmd.org/rules/index.html
phpmd_rules="cleancode,codesize,controversial,design,naming,unusedcode"
printf "✔︎ Formato de Output: ${color_bold_yellow}text${color_reset}\n"
printf "✔︎ Regras: ${color_bold_yellow}${phpmd_rules}${color_reset}\n"
printf "✔︎ Extensão: ${color_bold_yellow}php${color_reset}\n\n"
#message_info "PHPMD - PHP Mess Detector: [ ${staged_files_separated_by_comma} ]"
# PHPMD running script
phpmd_output=$(phpmd ${staged_files_separated_by_comma} text "${phpmd_rules}" --suffixes php)
phpmd_retval=$?
if [ $phpmd_retval -ne 0 ]; then
message_failure "PHPMD - PHP Mess Detector detectou erros, resolva-os e volte a comitar."
echo
printf "${phpmd_output}\n"
# Adding error message.
errors=("${errors[@]}" "$phpmd_output")
else
message_success '✔ Etapa sem erros!'
fi
echo "\n\n-------------------------------------------"
echo "- ${color_bold_cyan}PHPStan - PHP Static Analyses${color_reset}"
echo "-------------------------------------------\n"
if ! hash phpstan 2>/dev/null; then
message_warning "PHP Stan Analyses não foi encontrado!"
message_info "Visite: https://phpstan.org/user-guide/getting-started#installation"
exit 1
fi
# PHPSTAN running script
phpstan_output=$(phpstan analyse ${staged_files_separated_by_space} --level=8 -a "${CURRENT_DIR}/vendor/autoload.php" -c "${CURRENT_DIR}/phpstan.neon" --memory-limit=-1)
phpstan_retval=$?
if [ $phpstan_retval -ne 0 ]; then
message_failure "PHPSTAN - PHP Stan Encontrou alguns erros. Resolva e volte a comitar."
printf "${phpstan_output}\n"
# Adding error message.
errors=("${errors[@]}" "$phpstan_output")
else
message_success '✔ Etapa sem erros!'
fi
echo "\n\n-------------------------------------------"
echo "- ${color_bold_cyan}PHP Copy/Paste Detector (PHPCPD)${color_reset}"
echo "-------------------------------------------\n"
if ! hash phpcpd 2>/dev/null; then
message_warning "PHP Copy/Paste Detector não foi encontrado!"
printf "${color_bold_white}Por favor instale o pacote: phpcpd, e.g.:${color_reset}\n"
exit 1
fi
phpcpd_arguments="--no-interaction --progress --min-lines=3 --min-tokens=40"
# PHPCPD running script
phpcpd_tmp=/tmp/t$$
phpcpd ${phpcpd_arguments} ${staged_files_separated_by_spaces} > $phpcpd_tmp
if grep -q 'Found' $phpcpd_tmp
then
message_failure "PHPCPD - PHP Copy/Paste Detector encontrou erros, resolva-os e volte a comitar!"
phpcpd_output="`cat $phpcpd_tmp`"
printf "${phpcpd_output}\n"
# Adding error message.
errors=("${errors[@]}" "$phpcpd_output")
else
message_success "✔ Sem erros - PHPCPD!"
fi
# Cleanup
rm /tmp/*.$$ 2>/dev/null
rm /tmp/*$$.txt 2>/dev/null
rm -f $phpcpd_tmp
fi
# If we have errors, exit with 1
if [ -n "$errors" ]; then
message_failure 'Por favor corrija os erros e volte a fazer o commit!'
exit 1
fi
echo "\n\n-------------------------------------------"
echo "- ${color_bold_green}Nenhum erro encontrado! 👏 👏 👏 👏${color_reset}"
echo "-------------------------------------------\n"
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment