Skip to main content

Git Hooks

380 words·2 mins

An overview on using Git hooks in a Git repo, to automate any task such as style checking, notification, deployment, etc.

Git hooks #

Local hooks #

suitable for style checking, auto format, lightweight unit testing …

In any Git repository, you can view the existing hook scripts with this command:

$ ls .git/hooks/
pre-commit.sample
pre-push.sample
...

Any file in there ending with .sample are for example purposes. To use any of them, simply read (and modify as needed) the example file, and then remove the .sample suffix from the file name.

Git will start triggering the hook at the specified time (based on the file name) for you.

Sharing local hooks #

Most of the time you’ll want the hooks to be effective for all other project contributors when they run git command on their machine.

To share the files under .git/hooks/ with the team, I recommend moving them out of the .git/ directory, into another directory such as hooks/, in order to also check them into the remote Git repo.

With this setup, you and other team member will need to run this command once to redirect where Git finds the hook scripts:

$ git config core.hooksPath hooks

Server-side hooks #

There are 3 server-side hooks:

  • pre-receive
  • update
  • post-receive

They could be useful if you look to enforce some policy for your project or configure a lightweight CI/CD pipeline. These hook scripts also stay in the directory .git/hooks/, but on the server. Since they are still outside of the Git repo, you’d need to manually put them there (that is, you can’t add and push them via a regular Git push).

Webhooks on Git hosting services #

suitable for CI/CD

You can integrate the hosted Git repo with other wither systems for integration testing, staging and production deployment via services such as Jenkins, CircleCI, web hosting solutions, etc.

In the simplest form, when there is a new commit to the master or the release branch, you can have a web request sent to the CI/CD system to trigger the test suite and then deployment on green test results.

The initial configuration can be very simple. Check out guides from your Git repo services, for example:

Learn more #