Mercurial pre commit hook - stop commit based on file contents?

BTW, on Windows you can use

[hooks]
pretxncommit.nocommit = hg export tip | findstr NOCOMMIT && EXIT /B 1 || EXIT /B 0

This hook will fail if your sources contains string "NOCOMMIT"


Ry4an's answer is almost correct :) but you need to replace "hg export tip" with "hg diff".
tip is the last commited changeset, but are interested in local uncommited changes - so diff is what u need. for my needs i added the following to my hgrc

precommit.removeDebug = hg diff -S | grep -v '^-' | (! egrep '(var_dump)|(exit)|(print_r)')

the -S includes subrepos (maye not need, and may be still buggy).
the grep -v '^-' removes lines from the diff that indicate lines that were removed. i removed the -q so i at least have a idea what to remove, but unfortunatly this method cannot print you the file and linenumber of the occurence (as it is piped). maybe someone has a better way to do it.


Chapter 10 of the mercurial book covers this exactly:

$ cat .hg/hgrc
[hooks]
pretxncommit.whitespace = hg export tip | (! egrep -q '^\+.*[ \t]$')
$ echo 'a ' > a
$ hg commit -A -m 'test with trailing whitespace'
adding a
transaction abort!
rollback completed
abort: pretxncommit.whitespace hook exited with status 1
$ echo 'a' > a
$ hg commit -A -m 'drop trailing whitespace and try again'

In this example, we introduce a simple pretxncommit hook that checks for trailing whitespace. This hook is short, but not very helpful. It exits with an error status if a change adds a line with trailing whitespace to any file, but does not print any information that might help us to identify the offending file or line. It also has the nice property of not paying attention to unmodified lines; only lines that introduce new trailing whitespace cause problems.

Just change the regular expression from '^\+.*[ \t]$' to whatever string you're looking for.