DiegoSalazar DiegoSalazar - 24 days ago 8
Bash Question

how to not forget to delete debug lines in code

This seems to me to be a novel idea (since i haven't found any solutions or anyone having implemented it)...

A shell script that automatically runs whenever you git commit or whatever that will let you know if you forgot to delete any debugging or development env specific lines of code in your project.

For example:

Often times (in my Ruby projects) I'll leave lines of code to output variables like

puts params.inspect


raise params.inspect

Also, sometimes I'll use different methods so I can easily see the effects such as in cases like using delayed_job where I'd rather call the method without a delay during development.

The problem is sometimes I forget to change those methods back or forget to delete a call to raise params.inspect and I'll inadvertently push that code.

So I thought maybe the simplest solution was to add a comment to any such debugging line such as

raise params.inspect #debug

In essence flagging that line as a development only/debug line. Then in a shell script that runs before some other command like git commit it can use awk or grep to search through all the latest modified files for that #debug comment and stop execution and alert you. However i don't know much about shell scripting so I thought I'd ask for help :)

Answer Source

Although I whole-heartedly recommend following cdeszaq'a advice and discourage doing this sort of thing, it is pretty easy to write a git hook that will prevent you from committing any lines with a particular string. For simplicity, I'm not showing the git rev-parse --verify HEAD that you should use to make this hook work on an initial commit, but if you simply put the following in .git/hooks/pre-commit (and make it executable), you will not be able to commit any lines of code that contain the string '#debug':


if git diff-index -p -M --cached HEAD | grep '#debug' > /dev/null; then
  echo 'debug lines found in commit.  Aborting' >&2
  exit 1