Last active
April 20, 2021 07:25
-
-
Save timheilman/1bb8da91be4b79425d67314c9ae23f6b 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. Itself passes rubocop with default settings.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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("' '") | |
system("rubocop '#{changed_files}'") unless changed_files.empty? | |
exit $CHILD_STATUS.to_s[-1].to_i |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How to check if staged or committing file is not (.txt, .pdf, .dll) in ruby?