Skip to content

Instantly share code, notes, and snippets.

@ty-porter
Last active November 13, 2019 17:38
Show Gist options
  • Save ty-porter/f41fc95169f77967d2f4378bbab12567 to your computer and use it in GitHub Desktop.
Save ty-porter/f41fc95169f77967d2f4378bbab12567 to your computer and use it in GitHub Desktop.
A simple pre-commit hook to halt commits if Rubocop fails. Can be overridden if necessary.
#!/usr/bin/env ruby
require 'english'
require 'rubocop'
ADDED_OR_MODIFIED = /A|AM|^M/.freeze
changed_files = `git status --porcelain`.split(/\n/).
select { |file_name_with_status|
file_name_with_status =~ ADDED_OR_MODIFIED
}.
map { |file_name_with_status|
file_name_with_status.split(' ')[1]
}.
select { |file_name|
File.extname(file_name) == '.rb'
}.join(' ')
success = system(%(rubocop #{changed_files}))
STDIN.reopen('/dev/tty')
if success == false
puts "Would you like to continue? Press any key or 'n/N' to halt commit."
exit(1) if %w(N n).include?(gets.chomp)
end

Pre-Commit Hook

Place pre-commit.sh into your project's root directory, then before making changes to your repository, copy pre-commit.sh to the repo .git/hooks folder using:

ln -s ../../pre-commit.sh .git/hooks/pre-commit

This hook halts your commit if there are any Rubocop errors. You can abort the commit with n/N or ignore warnings and commit anyway with any other key.

Best practice is to abort the commit and run rubocop -a to attempt to autocorrect any errors, and manually correct any remaining complaints. Then, re-add your files and commit again. For instance:

git add .
git commit -m "Commit message"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment