Writing Your Own Hooks

When you are writing a hook, you might find it useful to run Mercurial either with the -v option, or the verbose config item set to true. When you do so, Mercurial will print a message before it calls each hook.

Choosing How Your Hook Should Run

You can write a hook either as a normal program—typically a shell script—or as a Python function that is executed within the Mercurial process.

Writing a hook as an external program has the advantage that it requires no knowledge of Mercurial’s internals. You can call normal Mercurial commands to get any added information you need. The trade-off is that external hooks are slower than in-process hooks.

An in-process Python hook has complete access to the Mercurial API, and does not shell out to another process, so it is inherently faster than an external hook. It is also easier to obtain much of the information that a hook requires by using the Mercurial API than by running Mercurial commands.

If you are comfortable with Python or require high performance, writing your hooks in Python may be a good choice. However, when you have a straightforward hook to write and you don’t need to care about performance (probably the majority of hooks), a shell script is perfectly fine.

Hook Parameters

Mercurial calls each hook with a set of well-defined parameters. In Python, a parameter is passed as a keyword argument to your hook function. For an external program, a parameter is passed as an environment variable.

Whether your hook is ...

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.