Andrew Udvare is a web developer based in the San Francisco Bay Area whose interests include web and mobile application development.
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[code language="bash"]
git clone firstname.lastname@example.org:symfony/symfony.git
In that directory, you will see something like:[code language="bash"]
We will focus on the
pre-commithook which runs prior to allowing a commit.