Skip to content

Instantly share code, notes, and snippets.

@unixmonkey
Last active August 1, 2018 20:34
Show Gist options
  • Save unixmonkey/aa56cca0040dfeee69de to your computer and use it in GitHub Desktop.
Save unixmonkey/aa56cca0040dfeee69de to your computer and use it in GitHub Desktop.
git pre-commit hook to prevent check-in of debugger stuff
#!/usr/bin/env ruby
# This pre-commit hook aims to prevent you from *accidentally* committing debugger
# statements if installed in your project. You can force a commit if necessary with:
# `git commit --no-verify`.
# Install by copying it to <your-project-dir>/.git/hooks/pre-commit'
hits = []
rb_debuggers = ['binding\.pry', 'binding\.remote_pry', 'debugger', 'focus: true', ':focus => true', 'save_and_open_page', 'save_and_open_screenshot']
js_debuggers = ['console\.log', 'debugger']
checks = {
'_spec\.rb$' => rb_debuggers,
'\.rb$' => rb_debuggers,
'\.erb$' => rb_debuggers,
'\.haml$' => rb_debuggers,
'\.slim$' => rb_debuggers,
'\.coffee' => js_debuggers,
'\.js' => js_debuggers,
'\.jsx' => js_debuggers
}
# Find the names of all the filenames that have been (A)dded (C)opied or (M)odified
filenames = `git diff --cached --name-only --diff-filter=ACM`.split("\n")
filenames.each do |filename|
# Perform special checks for _spec filenames (rspec tests)
checks.each do |filename_pattern, patterns|
if filename.match filename_pattern
patterns.each do |contents_pattern|
results = `git diff --cached #{filename} | grep "^\+[^+]" | grep "#{contents_pattern}"`.split("\n").map { |r| r.sub(/^\+[\s\t]*/, '') }
if $? == 0
# Add the relevant change with line number to the hits array
results.each{ |r|
hits.push "#{filename}:" + `grep -n '#{r}' #{filename}`.sub(/:\s+/, ' ').chomp
}
end
end
end
end
end
if hits.any?
puts "\e[33m>>> Please remove the following problems from these files before committing\e[0m"
puts hits.join("\n")
puts "or force your commit by passing --no-verify"
end
exit 1 if hits.any?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment