Andrew Udvare is a web developer based in the San Francisco Bay Area whose interests include web and mobile application development.

Andrew's articles

  1. An Introduction to Git Hooks

    Git hooks are simple scripts that run before or after certain actions. They are useful for a variety of tasks, but primarily I find them useful for client-side validation so simple mistakes can be prevented. For example, you can test syntax on files being commited, you can even have tests run. I have written hooks that validate Twig syntax, run JSHint to a standard, and a lot more.

    Git hooks are also extremely simple by design. Git will run these hooks if the script is executable and Git will allow the action (e.g. commit or push) to occur as long as the hook exits with no errors (status 0). Hooks can be written in any language the environment can work with.

    There are two types of hooks:

    • Client-side – These run on the developer’s system
    • Server-side – These run on the server hosting the Git repository

    Server-side hooks will not be covered in this article. However, do note that if your project is on a service like GitHub, server-side hooks are generally not applicable. On GitHub, the equivalent to server-side hooks is to use services and Webhooks which can be found in your project settings.

    The Hook Files

    Every repository including those you clone by default will have example hooks in the .git/hooks directory:

    [code language="bash"]
    git clone git@github.com:symfony/symfony.git
    cd symfony
    ls .git/hooks
    [/code]

    In that directory, you will see something like:

    [code language="bash"]
    applypatch-msg.sample
    commit-msg.sample
    post-update.sample
    pre-applypatch.sample
    pre-commit
    pre-commit.sample
    prepare-commit-msg.sample
    pre-push.sample
    pre-rebase.sample
    update.sample
    [/code]

    We will focus on the pre-commit hook which runs prior to allowing a commit.