Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

How can I setup a pre-commit hook , that will search for a string in the committed files and If found stop the commit ?

like image 300
johnlemon Avatar asked Nov 12 '10 07:11

johnlemon


People also ask

How do you ignore a pre-commit hook?

Use the --no-verify option to skip git commit hooks, e.g. git commit -m "commit message" --no-verify . When the --no-verify option is used, the pre-commit and commit-msg hooks are bypassed.

Can you commit pre-commit hooks?

pre-commit hooks are a mechanism of the version control system git. They let you execute code right before the commit. Confusingly, there is also a Python package called pre-commit which allows you to create and use pre-commit hooks with a way simpler interface.

How do I temporarily disable pre-commit?

Quick tip if you want to skip the pre-commit validations and quickly want to get a commit out there. To get your commit through without running that pre-commit hook, use the --no-verify option. Voila, without pre-commit hooks running!


2 Answers

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.

like image 162
Ry4an Brase Avatar answered Oct 11 '22 09:10

Ry4an Brase


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.

like image 42
Jonas Avatar answered Oct 11 '22 08:10

Jonas