Skip to content

Instantly share code, notes, and snippets.

@anujbiyani
Last active June 18, 2020 18:01
Show Gist options
  • Save anujbiyani/169d3bb95baa0e424e031a16f6b09987 to your computer and use it in GitHub Desktop.
Save anujbiyani/169d3bb95baa0e424e031a16f6b09987 to your computer and use it in GitHub Desktop.
A pre-commit hook to run Rubocop. Adapted from another gist (see comment on line 3), but updated to run autocorrect for you and commit the changes.
#!/usr/bin/env ruby
# adapted from https://gist.github.com/stevenharman/f5fece7fd39356e57ce3c710911f714f
RED = "\033[0;31m"
GREEN = "\033[0;32m"
NO_COLOR = "\033[0m"
if `command -v bundle exec rubocop` == ""
puts "💀#{RED} Install Rubocop and be sure it is available on your PATH#{NO_COLOR}"
puts "ℹ️ Try 'gem install rubocop'"
exit 1
end
suspects = `git diff --staged --name-only --diff-filter=AMC *.rb`.split("\n").map(&:strip).join(" ")
exit 0 if suspects.empty?
changes_to_stash = !`git diff --name-only`.empty?
if changes_to_stash
changed_files = `git diff --staged --name-only`.split("\n").map(&:strip).join(" ")
`git commit --no-verify --message='temporary commit to create a clean stash'`
`git stash push --quiet`
`git reset HEAD^`
`git add #{changed_files}`
end
puts "🚔 Linting files: #{suspects}"
if system("bundle exec rubocop --auto-correct #{suspects}")
`git add #{suspects}`
exit_status = 0
puts "🎉#{GREEN} Rubocop is appeased.#{NO_COLOR}"
else
puts "#{RED}💀 Rubocop found some issues it wasn't able to auto-correct. Fix, stage, and commit again#{NO_COLOR}\n"
exit_status = 1
end
`git stash apply --quiet && git stash drop --quiet` if changes_to_stash
exit exit_status
@anujbiyani
Copy link
Author

It will stash changes that are not staged before running and unstash them after running. But because autocorrect must run on whole files, it will correct and commit all violations in a staged file instead of just staged violations.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment