Upgrade Your Drupal Skills

We trained 1,000+ Drupal Developers over the last decade.

See Advanced Courses NAH, I know Enough

Stop your builds failing with git pre commit hooks

Parent Feed: 

Have you ever happily pushed your latest piece of work ready for others to test only to have it fail the build on coding standards? If so, git pre commit hooks could be your friend!

It's pretty standard practice these days for CI build pipelines to include linting steps to ensure things like coding standards pass. Depending on how the build is configured, failing coding standards can result in the entire build failing. 

Because linting is generally not resource intensive, running it locally can be a useful time saver. But it's an easy step to forget. Thankfully it can be automated to run before every git commit with a pre-commit hook.

First we need a script to fire before the commit. This is placed in the project repo somewhere like .git-hooks/pre-commit:

#!/bin/sh

make lint-php
exit $?

We use Makefiles to call our custom lint-php rule, but this could be a Robo command or any other task running which fires your coding standard check.

Next, the script needs to be executable:

chmod +x .git-hooks/pre-commit

Then let git know about this script by running the following command:

git config core.hooksPath .git-hooks

That's it, our coding standards check will now automatically run whenever we do a git commit and stop the commit from proceeding if there is a fail.

If you've got a WIP or something you wish to commit regardless of any errors use git commit --no-verify

Hopefully this saves you from pushing coding standard fails in the future.

Author: 
Original Post: 

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web