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

08 / Nov / 2022 by Rajveer Singh 0 comments

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:

  1. Create hooks directory on root project.
  2. Create a pre-commit file in the hooks directory.
  3. 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);\""
      ]
}
Now execute Composer install in your project directory
Composer install will mv hooks/pre-commit file to .git/hooks/pre-commit.

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.

FOUND THIS USEFUL? SHARE IT

Tag -

Drupal

Leave a Reply

Your email address will not be published. Required fields are marked *