Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Rubocop pre-commit hook
#!/usr/bin/env ruby
# Grab a list of staged changed files
changed_files = `git diff --name-only HEAD`.split("\n")
should_fail, broken_files = false, []
changed_files.each do |file|
# Run static code analysis on changed file
output = `rubocop #{file} --format simple`
# Get exit code of Robocop. Returns a non-zero exit code if it fails.
exit_code = $?.to_i
# If Rubocop is not installed, handle gracefully.
if exit_code == 127
puts 'It appears that Rubocop is not installed. Please run `bundle install` or `gem install rubocop.`'.yellow
exit 0
end
# Grab all lines of the output.
lines = output.split("\n")
# 2nd through -3rd line are the actual errors
errors = lines[1..-3]
unless exit_code == 0
# The commit will fail
should_fail = true
broken_files << {
path: file,
errors: errors
}
end
end
if should_fail
puts 'Static Code Analysis Failed'.red
puts '---------------------------'.red
error_count = 0
# Produce a nice output for the user.
broken_files.each do |f|
puts " - #{f[:path]}".yellow
f[:errors].each do |error|
error_count += 1
puts " #{error}".red
end
print "\n"
end
puts "Detected #{error_count} errors in #{broken_files.count} files.".red
# Do not allow them to commit.
exit 1
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.