Search code examples
gitcommitpre-commit-hookcommit-message

How to make Git pre-commit behavior depend on commit message?


I know that to make git check the commit message before committing you can implement hooks/commit-msg. But now imagine a case where you want to let the hooks/pre-commit script behave differently based on the commit message?

For example (in a very loose environment) you might want to check whether you have a [nocheck] tag in your commit message which always lets your commit-check pass.

Or - in a more strict environment - you might want to have every file commented (and thus listed separately).

Or you might want to check the ticket ID against the related files.

etc...

Is there a way to accomplish this apart from doing the actual check in commit-msg (which seems to be counter-intuitive)?


Solution

  • But now imagine a case where you want to let the hooks/pre-commit script behave differently based on the commit message?

    This is not possible because there is no commit message when it is fired ...

    The pre-commit hook is run first, before you even type in a commit message.


    Is there a way to accomplish this apart from doing the actual check in commit-msg (which seems to be counter-intuitive)?

    The way to do it is precisely using commit-msg :

    The commit-msg hook takes one parameter, which again is the path to a temporary file that contains the current commit message. If this script exits non-zero, Git aborts the commit process, so you can use it to validate your project state or commit message before allowing a commit to go through.