Using git hooks to check syntax errors

Git is currently my favorite source code versioning tool and while I used Subversion, I knew about something called hooks that I never used.

Essentially, hooks allow you to execute custom scripts when you perform certain actions on your repository like committing files, pulling updates and so on. This is a very useful as you can write hook scripts to (say for example) automatically ftp a file to your web server when a change has been made.

A whole lot of really cool hook scripts have been written and if you use any code versioning tools, you should check out the ones that have been written for the tool you use.

In particular, I find that sometimes developers could check in code that has syntactic bugs. This happens in environments where there are no strict code testing rules. It can be really annoying when you or someone else does this and you have to fix that and then commit again… not professional at all. So I came across this post by Travis Swicegood that lists code that does a php lint on your PHP files before committing them to the repository. PHP lint (php -l) basically checks the syntax of your code and either gives an “ok” or prints the offending line.

For one of the projects I’m working on, I had to change line 11 of Travis’ code to read:

$filename_pattern = '/\.(php|engine|theme|install|inc|module|test)$/';

instead of

$filename_pattern = '/\.php$/';

If you’ve done Drupal coding, you’ll quickly recognize that :)

September 25, 2009

3 responses to Using git hooks to check syntax errors

  1. Anonymous said:

    Or, if you want to embrace the power of plain-old-shellscript, just try:

    #!/bin/sh
    git diff-index –cached –name-only HEAD | grep -E '.(php|module|inc)$' | while read FILE; do
    php -l $FILE >/dev/null || exit 1
    done
    exit 0
    :)

    • Phil Freo said:

      Your post only half works for me – it prints an error, but is not preventing the commit from occurring.

      • Tim said:

        Which versions are you using? The bash script hook or the PHP one. Also, which files are you trying to commit to the repository?

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>