Check Drupal coding standard by phpcs in git pre-commit hook

In this tutorial, you will learn how to improve the custom code, theme and module, and general code development by using the pre-commit hook on git. Git pre-commit validates Drupal coding standards on files before committing them and returns a message to fix each line of code on the files having errors.
Follow the next steps to set up the pre-commit git hook with Drupal coding standards:
- Create hooks directory on root project.
- Create a pre-commit file in the hooks directory.
- Add the below pre-commit code to the hooks/pre-commit file.
#!/bin/bash
STANDARD="Drupal"
BIN="./vendor/bin"
echo
echo "Drupal Coder pre-commit hook – commit with the --no-verify option to skip the hook"
echo
# Check whether PHP_CodeSniffer can be found
if [ ! -f "$BIN/phpcs" ]
then
echo "Drupal Coder not found – is it installed? 'composer require drupal/coder'"
echo
exit 1
fi
# Retrieve staged files
FILES=$(git diff --cached --name-only --diff-filter=ACMR HEAD)
# Run the sniffer
echo "Running Drupal Coder."
echo
PHPCS=("$BIN/phpcs" "--standard=$STANDARD" "--filter=gitstaged" "--encoding=utf-8" "-p" ".")
"${PHPCS[@]}"
# Syntax Error
if [ $? != 0 ]
then
echo "Please fix each violations detected."
echo
exit 1
fi
# Syntax OK
if [ $? == 0 ]
then
echo "No violations detected"
echo
exit 0
fi
Add PHP commands on the scripts section of the composer.json file.
"scripts": {
"post-install-cmd": [
"php -r \"copy('hooks/pre-commit', '.git/hooks/pre-commit');\"",
"php -r \"chmod('.git/hooks/pre-commit', 0755);\""
]
}
How to use it
git commit -m "The commit message."
This is going to execute Drupal Coder on each file and returns messages on the terminal in case of finding errors on files.
