Git pre-commit hook for WordPress development

Authored by

As seen previously on this blog, in Contributing to WordPress Core via GitHub and Streamlining Contributions to WordPress Core via GitHub, there are instructions for how to get a Git repo set up for committing patches for WordPress Core. These posts also include instructions for how to set up Travis CI to restrict reporting linting errors to just the scope of the changed lines in the patch. Today our wp-dev-lib project has been improved so that the included Git pre-commit hook also only will report issues on the patch being committed. To be clear, the pre-commit hook will only look at changes that have been staged. If you have selectively staged files via git add -p to skip committing any debug statements, these unstaged changes will be ignored by the linters like PHP_CodeSniffer, JSHint, and JSCS. This pre-commit hook can greatly improve the quality (and reduce quantity) of commits since the checks will be performed before Travis CI sees them. The improved pre-commit hook is even more critical on projects for which Travis CI is not available, such as for repos hosted on BitBucket.

You can install the wp-dev-lib Git pre-commit hook into your clone for Inside the root of your repo, run the following Bash commands:

git clone dev-lib
cd .git/hooks && ln -s ../../dev-lib/pre-commit . && cd -
cat << XML > phpcs.ruleset.xml
<?xml version="1.0"?>
<ruleset name="WordPress Develop">
  <rule ref="WordPress-Core" />
  <rule ref="WordPress-Docs" />

You can now make commits on a feature branch for your WordPress develop repo clone and have the pre-commit hook ensure that your staged patch conforms to the WordPress coding standards.

Given that Git commits should be small and frequent, and given that PHPUnit tests can take a very long time to run, you can selectively disable PHPUnit for commits via:

DEV_LIB_SKIP=phpunit git commit

You can create a Git command alias for this for convenience (including tab completion) via:

git config --global alias.commit-without-phpunit \
  '!DEV_LIB_SKIP=phpunit git commit'

Then you can just run:

git commit-without-phpunit

For more information on wp-dev-lib project and how to configure for your plugins and themes, see the readme.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.