Skip to content

Instantly share code, notes, and snippets.

@kevinjalbert
Created May 1, 2014 20:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kevinjalbert/6c1c2af40d8365cc48c5 to your computer and use it in GitHub Desktop.
Save kevinjalbert/6c1c2af40d8365cc48c5 to your computer and use it in GitHub Desktop.
Executable to run rubocop only on added/modified files in a git repository
#!/usr/bin/env ruby
# Improved from https://gist.github.com/mpeteuil/6147292
require 'english'
require 'rubocop'
VALID_FILE_EXT = %w(.rb .rabl .rake)
ADDED_OR_MODIFIED = /^\s*(A|AM|M)/.freeze
class NotInRepository < StandardError; end
def get_repository(path = Dir.pwd)
ascender = Pathname.new(path).to_enum(:ascend)
repo_path = ascender.detect { |dir| (dir + '.git').exist? }
raise NotInRepository if repo_path.nil?
repo_path.to_s
rescue NotInRepository
puts "You must be within a Git repository to run this command."
exit 0
end
Dir.chdir(get_repository) do
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|
VALID_FILE_EXT.include? File.extname(file_name)
}.join(' ')
system("rubocop #{changed_files}") unless changed_files.empty?
end
exit $CHILD_STATUS.to_s[-1].to_i
@andxyz
Copy link

andxyz commented Mar 18, 2015

@Skipants You seen this? I need a git hook that just works. And I need you to do the work for me 😟

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