Skip to content

Instantly share code, notes, and snippets.

@acid
Last active April 6, 2020 16:15
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 acid/5ef745e9a5bdbd2683494a3df24b1386 to your computer and use it in GitHub Desktop.
Save acid/5ef745e9a5bdbd2683494a3df24b1386 to your computer and use it in GitHub Desktop.
Pre-commit script for our rails app
#!/usr/bin/env ruby
require 'rubocop'
require 'english'
ADDED_OR_MODIFIED = /A|AM|^M/
# to prevent code injection: system is a dangerous call
def raise_single_quote_error
raise ArgumentError, 'Single quotes are not allowed in filenames here.'
end
def extract_file_name(file_name_with_status)
file_name_array = file_name_with_status.strip.split(' ')
file_name_array.shift
fname = file_name_array.join(' ')
fname[0] = '' if fname[0] == '"'
fname[fname.length - 1] = '' if fname[fname.length - 1] == '"'
raise_single_quote_error if fname.include?("'")
fname
end
changed_files =
`git status --porcelain`
.split(/\n/)
.select { |file_name_with_status| file_name_with_status =~ ADDED_OR_MODIFIED }
.map { |file_name_with_status| extract_file_name file_name_with_status }
.select { |file_name| File.extname(file_name) =~ /.rb/ }
.join("' '")
unless changed_files.empty?
system("bundle exec rubocop --fail-level A -a '#{changed_files}'")
system("bundle exec erblint --lint-all -a '#{changed_files}'")
end
exit $CHILD_STATUS.to_s[-1].to_i
@acid
Copy link
Author

acid commented Jun 21, 2018

Installation

  • copy the contents of this file into .git/hooks/pre-commit
  • chmod 755 .git/hooks/pre-commit

Usage

This will trigger before every commit and prevent the commit from happening if something needs to be done. rubocop tries to automatically fix things for you. If you want to skip this, use the -n flag.

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