Agile Zone is brought to you in partnership with:

I am a programmer and architect (the kind that writes code) with a focus on testing and open source; I maintain the PHPUnit_Selenium project. I believe programming is one of the hardest and most beautiful jobs in the world. Giorgio is a DZone MVB and is not an employee of DZone and has posted 636 posts at DZone. You can read more from them at their website. View Full User Profile

All the Git hooks you need

09.06.2011
| 27933 views |
  • submit to reddit

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.

Published at DZone with permission of Giorgio Sironi, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Mark Twain replied on Sat, 2011/10/01 - 4:44am

I am a maniac of code cleanliness; this pre-commit will hard-remove trailing-whitespaces:
#!/bin/sh
#
# Force remove trailing-whitespaces (and carriage-return in linux)

if git rev-parse --verify HEAD >/dev/null 2>&1
then
	against=HEAD
else
	# Initial commit: diff against an empty tree object
	against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
fi

# Find files with trailing whitespace
for FILE in `exec git diff-index --check --cached $against -- | sed '/^[+-]/d' | cut -f1 -d: | uniq` ; do
	# Fix them!
	sed -i 's/\s\+$//' "$FILE"
	git add "$FILE"
done

exit

Giorgio Sironi replied on Sun, 2011/10/02 - 5:41am

It's also valid for any language. :)

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.