Skip to content

Instantly share code, notes, and snippets.

@tpayet
Last active July 25, 2017 13:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tpayet/9b53d9acd67ce54bdfa6228fc408fcf2 to your computer and use it in GitHub Desktop.
Save tpayet/9b53d9acd67ce54bdfa6228fc408fcf2 to your computer and use it in GitHub Desktop.
Rubocop pre-commit hook
#!/usr/bin/env ruby
# Copy/pasta from https://gist.github.com/andrewpage/b281314934b9c15b5073 without the custome str methods
# 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.`'
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'
puts '---------------------------'
error_count = 0
# Produce a nice output for the user.
broken_files.each do |f|
puts " - #{f[:path]}"
f[:errors].each do |error|
error_count += 1
puts " #{error}"
end
print "\n"
end
puts "Detected #{error_count} errors in #{broken_files.count} files."
# 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