Use githooks and NOCOMMIT comments to prevent dangerous commits

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the workflows category.

Last Updated: 2024-11-23

If you spike a feature the incomplete/insecure way first in order to understand the problem space, be sure to place copious comments (or a "NOCOMMIT" comment that triggers a git-hook block), so as to guarantee you don't accidentally push or deploy the insecure code.

Here's my story: I was writing some code for testing out invoicing solutions:

class ChargesController
  def index
    @charges = Charge.all
  end
end

What I planned to have (eventually) was scoping to the current_user:

def index
  current_user.charges
end

What actually happened is that a version of this that was NOT not limited to the current_user made it into production, i.e. this:

def index
  # I made this change because I wanted a faster feedback loop when manually
  # testing.
  @charges = Charge.all
end

The solution, in future, is to add a comment to catch when I proof-read a commit:

def index
  # NOCOMMIT
  @charges = Charge.all
end

Or better yet a githook pre-commit that scans for this:

BLACK_LIST="NOCOMMIT|debugger|binding.pry"

for FILE in $(git diff-index --name-status --cached HEAD -- | cut -c3-) ; do
  # Check if the file contains one of the words in LIST
  if rg "$BLACK_LIST" "$FILE"; then
    echo "$FILE has one of the black-listed words you don't want to commit. Please remove it"
    exit 1
  fi
done

exit 0