Use Git Hooks to Enforce Code Quality Checks Before Commit and Push

Git hooks for code quality: PHPCS before commit, tests before push

Code style errors and failing tests are cheapest to fix before they leave the developer’s machine. Git can run a script before each commit and before each push; if the script fails, the commit or the push is stopped. Kept in the repository and activated with one setting, the hooks are the same for the whole team.

Problem: Pull requests of a WordPress plugin regularly fail in CI because of coding standard errors and broken tests that nobody ran locally.

Solution: Store the hooks in a .githooks/ folder in the repository, point Git to it with git config core.hooksPath .githooks (set automatically from the Composer post-install-cmd), run PHPCS on the staged PHP files in pre-commit and PHPUnit in pre-push.

pre-commit: PHPCS on the staged files

#!/usr/bin/env bash
# .githooks/pre-commit
set -euo pipefail

files=$(git diff --cached --name-only --diff-filter=ACMR -- '*.php')
[ -z "$files" ] && exit 0

echo "PHPCS on staged files..."
echo "$files" | xargs vendor/bin/phpcs --standard=phpcs.xml.dist -q || {
    echo "Fix the errors (vendor/bin/phpcbf fixes many automatically) or commit with --no-verify."
    exit 1
}

Only the files in the commit are checked, so the hook stays fast also in an old code base with many existing warnings. --diff-filter=ACMR skips deleted files. The rules live in phpcs.xml.dist, typically the WordPress Coding Standards (wp-coding-standards/wpcs installed with Composer).

The check runs on the working copy of the files; if a file has both staged and unstaged changes, the unstaged ones are checked too. That is a known limitation of simple hooks, good enough in practice.

pre-push: the tests

#!/usr/bin/env bash
# .githooks/pre-push
set -euo pipefail

echo "PHPUnit..."
vendor/bin/phpunit --testdox --colors=never

The tests run once per push, not per commit, so committing stays quick. wp scaffold plugin-tests creates the PHPUnit setup for a plugin if it has none yet.

Activate the hooks for everybody

chmod +x .githooks/*
git config core.hooksPath .githooks
{
    "scripts": {
        "post-install-cmd": [ "git config core.hooksPath .githooks" ]
    }
}

Hooks in .git/hooks/ are not part of the repository; core.hooksPath (Git 2.9+) makes Git use the tracked folder instead. With the Composer script, everyone who runs composer install gets them.

Commit messages

#!/usr/bin/env bash
# .githooks/commit-msg
msg=$(head -n 1 "$1")
if [ ${#msg} -gt 72 ]; then
    echo "The first line of the commit message is longer than 72 characters."
    exit 1
fi

commit-msg receives the path of the message file as its first argument.

NOTE: git commit --no-verify skips the hooks, and that is intended for emergencies. The hooks are a convenience for developers; the real gate is CI running the same commands on every pull request. Git hooks can also deploy: Git hooks for theme deployments.