Git, NoGit

Posted on June 23, 2017 in hacks

Ever pushed unwanted code to a Git repo after a long debugging session? For example, a rogue statement looking like:

var count = GetCount();
Console.WriteLine("DEBUG>>>" + count); // debug

Or, maybe, your precious secret API key that you hard-coded by mistake? Or, the offensive comment you wrote down in despair late late last night?

Of course that has never happened to you because you are a 10x developer, but it happened to me. Until I saved this simple script as .git/hooks/pre-commit in my projects:

#!/bin/sh

if git diff --cached | grep -q 'nogit'
then
    cat <<\EOF
Error: found 'nogit' marker in files
EOF
    exit 1
else
    exit 0
fi

Simply, it looks for the nogit tag in the committed code, and refuses to proceed if the tag was found. All you have to do is remember to tag your quick and dirty code:

var count = GetCount();
Console.WriteLine("DEBUG>>>" + count); // nogit

And Git will just not accept to commit until you remove it.

Caveats

It probably is an old trick.

This is a very simple script. It does not make any difference between comments and code, so a nogit variable would be rejected. If you have ideas to improve it, please share.

Before you try: one cannot add hooks to a repository and have them automatically enabled on each clone. This is for security reason, so one cannot ship a script that e.g. wipes the entire hard-disk. So the hook has to be manually enabled on each repo you clone.

Unless something can be done with Git's core.hooksPath global setting. Not sure.

There used to be Disqus-powered comments here. They got very little engagement, and I am not a big fan of Disqus. So, comments are gone. If you want to discuss this article, your best bet is to ping me on Mastodon.