Some Hook Examples

Writing Meaningful Commit Messages

It’s hard to imagine a useful commit message being very short. The simple pretxncommit hook of the example below will prevent you from committing a changeset with a message that is less than ten bytes long.

$ cat .hg/hgrc
[hooks]
pretxncommit.msglen = test `hg tip --template {desc} | wc -c` -ge 10
$ echo a > a
$ hg add a
$ hg commit -A -m 'too short'
transaction abort!
rollback completed
abort: pretxncommit.msglen hook exited with status 1
$ hg commit -A -m 'long enough'

Checking for Trailing Whitespace

An interesting use of a commit-related hook is to help you to write cleaner code. A simple example of cleaner code is the dictum that a change should not add any new lines of text that contain trailing whitespace. Trailing whitespace is a series of space and tab characters at the end of a line of text. In most cases, trailing whitespace is unnecessary, invisible noise, but it is occasionally problematic, and people often prefer to get rid of it.

You can use either the precommit or pretxncommit hook to tell whether you have a trailing whitespace problem. If you use the precommit hook, the hook will not know which files you are committing, so it will have to check every modified file in the repository for trailing white space. If you want to commit a change to just the file foo, but the file bar contains trailing whitespace, doing a check in the precommit hook will prevent you from committing foo due to the problem with bar. This ...

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.