Skip to content

Instantly share code, notes, and snippets.

@ndbroadbent
Forked from mpeteuil/rubocop_pre_commit_hook
Last active July 7, 2018 20:14
Show Gist options
  • Save ndbroadbent/615241731b8039606a0d316efb376893 to your computer and use it in GitHub Desktop.
Save ndbroadbent/615241731b8039606a0d316efb376893 to your computer and use it in GitHub Desktop.
Ruby style guide git pre-commit hook using Rubocop as the style guide checker. Only runs on staged ruby files that have been added and/or modified.
#!/usr/bin/env ruby
require 'english'
ADDED_OR_MODIFIED = /A|AM|^M/
added_or_modified = `git status --porcelain`.split("\n").select do |file_name_with_status|
file_name_with_status =~ ADDED_OR_MODIFIED
end
filenames = added_or_modified.map do |file_name_with_status|
file_name_with_status.split(' ')[1]
end
changed_ruby_files = filenames.select { |file| File.extname(file) == '.rb' }
exit if changed_ruby_files.empty?
puts 'Running Rubocop...'
system('rubocop', '-a', *changed_ruby_files)
rubocop_status = $CHILD_STATUS
system('git', 'add', *changed_ruby_files)
unless rubocop_status.success?
puts "\nPlease fix rubocop errors before committing changes."
exit rubocop_status.to_s[-1].to_i
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment