Git pre-commit hook script for Ruby on Rails projects
If you have ever worked on a Ruby on Rails project that uses Git for version control, odds are that you have run into a scenario where you (or other developers on your team) have accidentally committed a debugger statement or a binding.pry and checked it into the Git repo.
One of the developers on our team at Attribytes recently shared a really cool script that he found which checks for common debugger statements in your code every time someone commits code to Git, and halts the commit if an offending line is found.
The script worked pretty well, but it was throwing a lot of false positives and it was lacking some features I wanted (such as an ignore list), so I modified it to fit our needs.
Here’s the resulting script:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
# This script verifies if a list of "undesired" words are presented in the files you are # intended to commit such console output, debugging information or keys/tokens/passwords. # Instructions: # Put this file into your .git/hooks folder as a file named "pre-commit", and set # the file as executable (chmod +x pre-commit) # If you want to skip the hook just add the --no-verify: git commit --no-verify # If you want to ignore specific files, create a text file called ".pre-commit-ignore" # and place it at the root of your Git project (next to your .gitignore file), and put the names # of each file you want to ignore on each line, like so: # # Example .pre-commit-ignore file contents: # # Gemfile # Gemfile.lock # config/initializers/example_file_to_ignore.rb # # --------------------------------------------- #!/bin/sh # Modify this # LIST='list\|of\|words\|splitted\|by\|slash\|and\|pipe' LIST="byebug\|debugger\|binding.pry\|console.log(" PROJECT_ROOT=$(git rev-parse --show-toplevel) IGNORED_FILES="$PROJECT_ROOT/.pre-commit-ignore" if git rev-parse --verify HEAD >/dev/null 2>&1; then against=HEAD else against=4b825dc642cb6eb9a060e54bf8d69288fbee4904 fi for FILE in `git diff-index --name-status --cached $against -- | cut -c3-` ; do # Skip checks on any ignored files if [[ -f "$IGNORED_FILES" ]]; then if grep -q "$FILE" "$IGNORED_FILES"; then continue fi fi # Check if the file contains one of the words in LIST if grep -w $LIST $FILE; then echo "$FILE has one of the debugging statements that you don't want to commit! Please remove it or run git commit with the --no-verify flag." exit 1 fi done exit |
For bonus points, place this script into the root of your project itself as a file named “pre-commit” and check it into the git repo. You could also include a little shell script to make it easy for everyone who works on the project to quickly install the hook!
install-git-pre-commit-hooks.sh:
1 |
mkdir -p ./.git/hooks && cp pre-commit ./.git/hooks/pre-commit && chmod +x ./.git/hooks/pre-commit |