201702.01

Debug comments (or how to save your sanity using git)

A lot of times when I’m programming, I need to write a few lines of code that test what I’m working on. This can be a top-level function call, a few log entries, etc. Much to my dismay, I tended to end up with this debug code committed to git.

I decided I wasn’t going to take it anymore.

Git’s pre-commit hook to the rescue

Now, whenever I add one of these lines, I mark it with a special comment:

console.log('the value is: ', val);     // gee, sure hope i don't commit this

becomes

// DEBUG: remove this log entry
console.log('the value is: ', val);

Then in my pre-commit hook, I symlink a script that checks for DEBUG comments in various languages for that repo:

#!/bin/sh

DEBUG=""
function add_to_debug {
	filetype=$1
	comment=$2

	next=$(
		git diff \
			--cached \
			--name-only \
			-G"${comment}[ ]*DEBUG" \
			-- "*.${filetype}"
	)
	DEBUG="${DEBUG}${next}"
}

add_to_debug 'js' '//'
add_to_debug 'rs' '//'
add_to_debug 'html' '<!--'
add_to_debug 'lisp' ';'
add_to_debug 'sh' '#'
add_to_debug 'hbs' '{{!--'

if [ "${DEBUG}" != "" ]; then
	echo
	echo "Please address the DEBUG comments in following files before committing:"
	echo
	echo "${DEBUG}" | sed 's/^/  /'
	exit 1
fi

Using this, trying to commit any code that has DEBUG comments will fail with the output:

Please address the DEBUG comments in following files before committing:

  user.js

This forces going back in and cleaning up your code before committing it. Wicked.

Get it yourself

Grab the pre-commit hook off my Github to END THE SUFFERING and stop committing your debug code.