DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Deployment
  4. All the Git hooks you need

All the Git hooks you need

Giorgio Sironi user avatar by
Giorgio Sironi
·
Sep. 06, 11 · Interview
Like (0)
Save
Tweet
Share
48.96K Views

Join the DZone community and get the full member experience.

Join For Free

Hooks are scripts that are called when certain events in the workflow of a source control system occur. In the case of Git, there are many possible hooks where you can intervene, like before and after a commit, or before some commits are rewritten by a Git command.

Most of the hooks have pre- and post- versions: you can stop a commit or another operation in case of non-conformance to some rules, or notify another application that the event occurred.

Git hooks are executable scripts (chmod +x), written in bash or any other interpreter. A shebang (#!) should indicate which interpreter should run the script.
The hooks are placed in the .git/hooks directory, so that they are customizable for each copy of a repository (.git is not under version control however.) All hooks have a hook_name.sample example copy in this directory, which you should rename to hook_name to activate.

Some hooks are called with arguments, but Git is pretty fast and generally you can obtain what you want with commands like git status and git diff.

Client side hooks

These hooks are run on a developer's workstation, mainly due to operation that involve new commit or modification of existing ones.
  • pre-commit is called before a commit occurs.
  • prepare-commit-msg lets you edit the default message before the editor is fired up; it's useful in automated commits to add some context.
  • commit-msg is the last step where you can interrupt a commit.
  • post-commit is executed after a commit is completed, for notification purposes.
Other client side hooks are not executed by the git commit command, and their names are self-explanatory:
  • pre-rebase
  • post-checkout
  • post-merge
Some special hooks need a description instead:
  • post-rewrite runs after some commits are amended or rebased.
  • pre-auto-gc runs before garbage collection takes place, and can interrupt it.

In most of this script exiting with a non-0 status will abort the commit, or the rebase, or the current operation; just as you expected.

Client side hooks are not transferred during cloning, as they are not even stored in the repository. Instead, they are copied from the folder /usr/share/git-core/templates/hooks on the machine where you create the repository.

To version control the hooks, put them in some directory inside the main tree (not in .git) like .hooks/, and then modify the local machine configuration:

cd /usr/share/git-core/templates/hooks/
sudo mv pre-commit.sample pre-commit.sample.old
sudo ln -s ../../.hooks/pre-commit pre-commit

The symlink will be copied to the new repository upon cloning, and it will point to an hook which is under version control. If the file or the folder .hooks does not exist, it will just be ignored.

Email workflow

git am uses these hooks (not a general case, but it's nice to know what they are). An email workflow means that patches are sent through alternative media (such as email attachments) instead of propagating commits via pushes and pulls. The hooks are:

  • applypatch-msg
  • pre-applypatch
  • post-applypatch

Server side

These hooks are run on the receiving side of a push:

  • pre-receive can be used to check and interrupt the receival of the new commits, if it is the case.
  • post-receive notifies that commits have been published on this repository.
  • update is a version of pre-receive that is run once per each different branch.
  • post-update is a notification activated after all references have been updated; the default hook updates some metadata to let the repository be published via HTTP.

A ready to use example

We'll concentrate on the client side: hooks are simpler to write and, if you have disciplined developers, handy for team-wide usage.

This script is a pre-commit: it uses the PHP interpreter lint to check there are no syntax errors. It's not like running the tests, but it's a fast smoke test that you can always make. This is a PHP version, but I'm sure you can reuse the git commands with another lint.

The hook runs only on the modified files; the 4b82... magic number means an empty tree in Git, and apparently is a fictional revision valid cross-repository.
I modified the original hook you can find online, as it was incomplete: whenever a .php file is removed from the repository, the commit died as php -l was executed on a non existent file.

#!/usr/bin/php
<?php
$output = array();
$rc     = 0;
exec('git rev-parse --verify HEAD 2> /dev/null', $output, $rc);
if ($rc == 0)  $against = 'HEAD';
else           $against = '4b825dc642cb6eb9a060e54bf8d69288fbee4904';

exec("git diff-index --cached --name-status $against | egrep '^(A|M)' | awk '{print $2;}'", $output);

$needle            = '/(\.php|\.phtml)$/';
$exit_status = 0;

foreach ($output as $file) {
    if (!preg_match($needle, $file)) {
        // only check php files
        continue;
    }

    $lint_output = array();
    $rc              = 0;
    exec('php -l '. escapeshellarg($file), $lint_output, $rc);
    if ($rc == 0) {
        continue;
    }
    echo implode("\n", $lint_output), "\n";
    $exit_status = 1;
}
exit($exit_status);

Resources

http://progit.org/book/ch7-3.html for the description of the some of the hooks.
http://www.kernel.org/pub/software/scm/git/docs/githooks.html for the official documentation, which shows how the hooks are invoked and their full list.
http://phpadvent.org/2008/dont-commit-that-error-by-travis-swicegood for the incomplete pre-commit script.

Hook Git Commit (data management)

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Tracking Software Architecture Decisions
  • 10 Best Ways to Level Up as a Developer
  • Comparing Map.of() and New HashMap() in Java
  • Solving the Kubernetes Security Puzzle

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: