PHP/Drupal Code Quality Quick Wins, Part 3: Automated Validation with Git pre-commit Hooks

Joeri Poesen //

Even within small, closely-knit teams introducing new ways of doing things can take its time being adopted across the board. This is where having a Git-based workflow pays off: by adding a pre-commit hook in your local repository you can automatically have Git run php -l and phpcs on the files affected by your commit. If the linting or code validation check fails, the commit will be aborted.

At first this may seem an aggressive move towards the development team but once everyone sees the benefits of working with uniformly formatted, properly documented, syntax-checked and standards-validating code, they’ll wonder how they ever got things done without this in place.

Setup and usage

To implement a hook simply add a shell script with the name of the hook in your project’s .git/hooks directory. Bash, php, ruby, python… any language is ok, as long as the shell script is executable and the language is supported on your system.

[text]
# 1. Add hook in your project’s ./git/hooks directory.
$ touch precommit

# 2. Make sure hook is executable.
$ chmod a+x pre-commit

# 3. Paste in our example, fetch it from [url] or add in your own hook.
[/text]

Now try to commit some non-validating code to your repository. If all goes well you’ll see the same output as if you’d run the checks manually. If you now run git status, you’ll see that your files are still staged, so the commit itself has been rolled back and you’re free to edit your code and retry the commit.

Where to go from here

There are a number of other analysis and testing tools you could integrate in your process, IDE and Git hooks. Not all of them make sense to auto-run on pre-commit though. Some scripts you’ll want to run on a test server, others on a build server… ultimately it’s up to you to see which tools fit into your process.

If you’ve got static analysis tools you integrate in your daily Drupal development process, do share!