#FIXME! git pre-commit hook
I use #FIXME comments all the time in my code and I am sure you do, too. Some of these comments stay for a really long time until they finally get fixed. But sometimes there are temporary changes in my code which definitely must not go live!
For example, when you have a method in your code which checks access for something and you want to test both cases – access denied and access granted. The easiest way is to hard code a return value of FALSE or TRUE without using the real logic. Easy to do, but also easy to forget. And after the next deployment access is granted all the time … or never, because you forgot to remove the temporary code after your test.
Git hook
Git hooks are great way to execute scripts at a certain time in your git workflow. And to avoid the situation described above, I thought about using a pre-commit hook.
The pre-commit hook is run first, before you even type in a commit message. It’s used to inspect the snapshot that’s about to be committed, to see if you’ve forgotten something, to make sure tests run, or to examine whatever you need to inspect in the code.
My idea was to use #FIXME! (with an exclamation mark) to emphasize the changes which must not go live at any circumstances. The git hook should check, if the latest changes contain a FIXME! and exit before committing. I ended up with these few lines I found somewhere on the internet (long before AI was a thing) changed to my needs.
#!/bin/sh
#
# Check for FIXME!
# Test whether the repository has a valid HEAD without printing anything
if git rev-parse --verify HEAD >/dev/null 2>&1
then
against=HEAD
else
# If it's the first commit, diff against an empty tree object
against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
fi
# Check if diff contains a FIXME! as a whole word but ignoring case
VAR=$(git diff --cached | grep -iw "fixme!")
if [ ! -z "$VAR" ]
then
echo "You've left a #FIXME! in one of your files! Aborting commit..."
# Exiting non-zero from this hook aborts the commit
exit 1
fi
Git config
But where to put the script? You can add hooks to the local .git folder in your project. In this case .git/hooks/pre-commit would be the correct file. Since I don't use project related hooks, I decided to add the script as a global hook which will work for every existing and new project. You can use any directory on your computer to store your custom hooks, but you have to tell git where to find it in the global git config file.
[core]
hooksPath = /my/custom/gitconfig/hooks
To verify, you can run the following command which lists all your global configs.
git config --global -l
One more thing …
Just for the record. You can bypass the pre-commit hook by using git commit --no-verify. But don't do it!
Links
Git General Helper #FIXME
What do you think?
Let's discuss on Mastodon