Skip to content

Instantly share code, notes, and snippets.

@kenton
Last active August 29, 2015 14:27
Show Gist options
  • Save kenton/c5e9d2dd53148aaaa876 to your computer and use it in GitHub Desktop.
Save kenton/c5e9d2dd53148aaaa876 to your computer and use it in GitHub Desktop.
git pre-commit hook to check for problem files before commiting
#!/usr/bin/env ruby
problems = []
checks = {
#'_spec\.rb$' => ['focus:[:space:]*true'],
'\.rb$' => [
'binding.pry',
'debugger',
'if true',
'if false'
]
}
# Get names of all files that have been (A)dded, (C)opied, or (M)odified
# and that are staged to be part of the next commit
filenames = `git diff --cached --name-only --diff-filter=ACM`.split("\n")
filenames.each do |filename|
checks.each do |filename_pattern, patterns|
if filename.match filename_pattern
patterns.each do |contents_pattern|
new_lines_of_code = `git diff --cached #{filename} | ag -Q "\+" | ag "#{contents_pattern}"`
results = new_lines_of_code.split("\n").map { |r| r.sub(/^\+[\s\t]*/, '') }
if $? == 0
# Add the relevant change with line number to the problems array
results.each{ |r|
problems.push "#{filename}:" + `ag -n '#{r}' #{filename}`.sub(/:\s+/, ' ').chomp
}
end
end
end
end
end
if problems.any?
puts "\e[33m>>> Please remove the following problems from these files before committing\e[0m"
puts problems.join("\n")
else
end
exit 1 if problems.any?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment