A Short Tutorial on Using Hooks

It is easy to write a Mercurial hook. Let’s start with a hook that runs when you finish a hg commit, and simply prints the hash of the changeset you just created. The hook is called commit.

All hooks follow the pattern in this example.

$ hg init hook-test
$ cd hook-test
$ echo '[hooks]' >> .hg/hgrc
$ echo 'commit = echo committed $HG_NODE' >> .hg/hgrc
$ cat .hg/hgrc
[hooks]
commit = echo committed $HG_NODE
$ echo a > a
$ hg add a
$ hg commit -m 'testing commit hook'
committed ffec6cdc3a79c21f42d9e0c8fa460ea72c1748e5

You add an entry to the hooks section of your ~/.hgrc. On the left is the name of the event to trigger on; on the right is the action to take. As you can see, you can run an arbitrary shell command in a hook. Mercurial passes extra information to the hook using environment variables (look for HG_NODE in the example).

Performing Multiple Actions Per Event

Quite often, you will want to define more than one hook for a particular kind of event, as shown below.

$ echo 'commit.when = echo -n "date of commit: "; date' >> .hg/hgrc
$ echo a >> a
$ hg commit -m 'i have two hooks'
committed e2b474b33334b9c332deeaa7a211f36b03266ac9
date of commit: Tue May  5 06:44:39 GMT 2009

Mercurial lets you do this by adding an extension to the end of a hook’s name. You extend a hook’s name by giving the name of the hook, followed by a full stop (the . character), followed by some more text of your choosing. For example, Mercurial will run both commit.foo and commit.bar ...

Get Mercurial: The Definitive Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.