I quite often use keywords surrounded in parenthesis in my code as temporary todo markers for Resharper's
Todo Explorer. One common keyword I use a lot is
(nocommit) to indicate something is temporary and shouldn't be committed to source control. This is where Git hooks come in very handy to stop me accidentally committing these temporary changes.
A Git hook is just a script that runs when a specific event occurs in Git. There are various events we can hook into, but I'm going to be focussing on the
pre-commit hook. For more information about hooks in general, see this link.
In each Git repository, there's the usual
.git folder containing all the Git information. Inside that is a directory called, yes you guessed it,
hooks! The hooks directory by default contains a list of example hook scripts - each suffixed with ".sample". To enable one of them, all you need to do is rename the file to remove the ".sample" extension.
So back to the problem of how to enforce my
(nocommit) keyword. Below is a
pre-commit script to do this ...
#!/bin/sh if git-rev-parse --verify HEAD >/dev/null 2>&1; then against=HEAD else against=4b825dc642cb6eb9a060e54bf8d69288fbee4904 fi for FILE in `git diff-index --cached --name-status $against -- | cut -c3-` ; do # Check if the file contains 'nocommit' if grep --quiet 'nocommit' $FILE; then echo $FILE ' contains nocommit!' exit 1 fi done exit
Now when you try to commit a file with the word 'nocommit', it'll fail with a message saying
<filename> contains nocommit!. Currently this script only matches against this single hardcoded keyword. It could be quite easily extended to support a list of keywords.
From time to time you may want to commit a banned word. An example might be where you just want a temporary local commit that you aren't going to push. If you're using SourceTree as a client, the dropdown option you can see when committing has a flag to temporarily skip the commit hooks.