Git Beyond the Basics: Hooks for Automation
This is part 5 of a 6-part series on Git commands.
A relatively little-known Git feature is its support for both client- and server-side hooks for automation. That may seem strange, for a fully distributed version control system with no proper sense of a privileged “server”, but it’s nevertheless possible to configure processes to run in the “server” sense as the result of a push. Working with hooks is a matter of writing scripts in the .git/hooks folder for a repository, so it’s straightforward for those accustomed to DevOps tasks. Client-side hooks are available for pre-commit, pre-rebase, post-checkout, and post-merge, etc. which provide a fair amount of flexibility. In contrast, server-side hooks are limited to pre- and post-receive as well as an update script that’s run once for each branch being updated. Consider the following example script:
#!/bin/sh echo Pre-commit hook executing – commit failed! exit 1
That isn’t a particularly interesting script, doing nothing more than displaying a message and exiting with a failure code. But when those contents are stored in a .git/hooks/pre-commit file, it means any attempt to commit will fail with that message.
And note well, Windows users: Git executes hook scripts with its own Windows port of the bash shell, so you can’t expect to include regular batch commands. You can, however, enjoy the power of *nix scripting instead. By default you’ll find the following in the .git/hooks folder:
applypatch-msg.sample commit-msg.sample post-update.sample pre-applypatch.sample pre-commit.sample pre-push.sample pre-rebase.sample prepare-commit-msg.sample update.sample
Those files provide examples of how to craft hook scripts for the various types of tasks for which they’re intended. Simply copy an example to the same name minus the .sample extension, edit it as needed, and the hook will be executed the next time it’s triggered. Those interested in more details should consult the Git Book documentation.