Jesús Amieiro

Automatically Checking Code Standards Before Committing

It is very common to forget to apply the code standards before committing. As a result, if you have a GitHub action set up to automatically review them, the action will fail.

In a WordPress/PHP project, we usually use PHP_CodeSniffer (phpcs) to detect violations of a defined coding standard, and PHP Code Beautifier and Fixer (phpcbf) to automatically correct coding standard violations.

To automatically execute both scripts when you try to commit the code with Git, you can use a Git hook: a script that Git runs before or after events such as committing or pushing. The pre-commit hook runs before the commit is completed. If this script exits with a non-zero status, the commit will be aborted.

To set this up, create or edit the .git/hooks/pre-commit file in my project directory:

touch .git/hooks/pre-commit

Then, make it executable:

chmod +x .git/hooks/pre-commit

Next, add this code to the pre-commit file:

#!/bin/ bash # Remove the space between "/" and "bash"

# Paths to the phpcs and phpcbf executables
PHPCBF="./vendor/bin/phpcbf"
PHPCS="./vendor/bin/phpcs -n"

# Run phpcbf to automatically fix coding standard issues
echo "Running phpcbf..."
$PHPCBF

# Run phpcs to check for coding standard violations
echo "Running phpcs..."
$PHPCS

# If phpcs fails (returns a non-zero exit code), prevent the commit
if [ $? -ne 0 ]; then
    echo "phpcs found coding standard violations. Commit aborted."
    exit 1
fi

echo "All checks passed. Proceeding with commit."

This script runs phpcbf to automatically fix coding standard issues. Then it runs phpcs to check for coding standard violations, and if it finds any violation, it exits.

Now, when you commit, this file is executed:

git commit -m "Add the the_title hook only when I am in the page"
Running phpcbf...
................... 19 / 19 (100%)
No fixable errors were found
Time: 1.8 secs; Memory: 12MB

Running phpcs...
................... 19 / 19 (100%)
Time: 145ms; Memory: 24MB

All checks passed. Proceeding with commit.

[local-import-pages 43e3e6a4] Add the the_title hook only when I am in the page
 2 files changed, 7 insertions(+), 3 deletions(-)
Exit mobile version