DONTCOMMIT: How I avoid committing debug code

  • Sometimes while developing you want to try out a new idea and make a swift change to your code.
  • Sometimes when you try to tackle a bug it's easier to add a short line that dumps a variable to the console to assure a piece of code is not the culprit before you swing the debugger hammer.
  • Sometimes when you are working on your master thesis or a blog post you want to write down a short reminder or a new thought to be elaborated later.

All of those cases have in common that you're writing temporary code that you don't want anyone else to ever see. And here arises the problem of how to keep track of your changes especially if you have to edit multiple files at once. Later when you want to make the commit with hundreds of changed lines it's too easy to overlook a small debug statement.

A nice solution comes with the help of the phrase DONTCOMMIT and a fitting git pre-commit hook.

Whenever I add a line I want myself to delete or change back later I put a DONTCOMMIT somewhere. Usually as a comment.

Additionally my hook file .git/hooks/pre-commit looks this way:

#!/bin/sh

for FILE in `git diff --cached --name-only` ; do
    # Check if the file contains 'DONTCOMMIT'
    if grep -q 'DONTCOMMIT' "$FILE"
    then
        echo $FILE ' contains DONTCOMMIT!'
        exit 1
    fi
done
exit

What it does is checking every staged file I want to commit for an occurrence of DONTCOMMIT and in the positive case returns an error code which makes git cancel the commit with an appropriate error message. As you see this is a bash script. In a Windows environment you will have to re-implement the hook accordingly.

One challenge was to find a phrase that you are very sure you will never want to write down, that makes some sense, that is easily perceivable - in the end you want to find it yourself and that is easy enough to write down - if you misspell it it doesn't work. I settled with DONTCOMMIT. Which might be a little too long but I eased the pain a bit with the help of my IDE of choice: NetBeans. (You may lower your eye brows again.)

I added a macro that I can trigger by pressing Ctrl + Alt + D that puts the cursor at the end of the line and inserts the kill phrase. I could make it add the commenting characters as well which would be // in 95% of my cases but since I handle different file formats regularly this is only a small inconvenience.

caret-end-line
" DONTCOMMIT"

The downside of this great workflow is that I have to disable it for adding this post to source control.

impressum