Last active
March 8, 2018 21:46
-
-
Save tiagopog/092a52ec349e5327321df0743bec7e78 to your computer and use it in GitHub Desktop.
Apply Rubocop linter but only on git diffs
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 | |
## | |
# Helpers | |
## | |
module Helper | |
module_function | |
def display_start(count:) | |
puts "Inspecting #{count} file(s)\n\n" | |
end | |
def display_end(count:, offenses:) | |
puts "#{count} file inspected, #{offenses.nonzero? || "no"} offense(s) detected" | |
end | |
def regex | |
@regex ||= { | |
ruby_file: /[\/\-_\w]+.rb$/, | |
not_commited_line: /0{8}\s+\(Not Committed Yet \d{4}\-\d{2}\-\d{2}\s{1}\d{2}:\d{2}:\d{2}\s{1}\-\d{4}\s+(\d+)\)/, | |
modified_or_created: /\s?(M|\?{2}\s)/, | |
offense: /^.+.rb:\d+:\d+:\sC:/ | |
} | |
end | |
def normalize_file_name(files) | |
files.map do |file| | |
file.split(regex[:modified_or_created]).last | |
end | |
end | |
def offenses_for(file) | |
linter_offenses(`rubocop #{file} | grep -E '\.rb:.+:.+' -A2`) | |
end | |
def offenses_on_diff_for(file) | |
changed_lines = `git blame #{file}` | |
.scan(regex[:not_commited_line]) | |
.flatten | |
linter_offenses(`rubocop #{file} | grep -E '\.rb:(#{changed_lines.join('|')})+:' -A2`) | |
end | |
def linter_offenses(result) | |
return 0 if result.empty? | |
puts result | |
result.scan(regex[:offense]).size | |
end | |
end | |
## | |
# Linter | |
## | |
file = ARGV[0].to_s | |
file_count = 1 | |
offenses = 0 | |
if !file.empty? && File.exist?(file) | |
Helper.display_start(count: file_count) | |
offenses += Helper.offenses_on_diff_for(file) | |
else | |
modified, created = `git status --porcelain` | |
.split(/\n/) | |
.select { |status| status =~ Helper.regex[:ruby_file]} | |
.partition { |status| status =~ /^\sM\s/ } | |
.map { |files| Helper.normalize_file_name(files) } | |
file_count = modified.size + created.size | |
Helper.display_start(count: file_count) | |
offenses += modified.map(&Helper.method(:offenses_on_diff_for)).reduce(:+) | |
offenses += created.map(&Helper.method(:offenses_for)).reduce(:+) | |
end | |
Helper.display_end(count: file_count, offenses: offenses) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment