Skip to content

Instantly share code, notes, and snippets.

@clifton
Created July 25, 2012 00:27
Show Gist options
  • Save clifton/3173611 to your computer and use it in GitHub Desktop.
Save clifton/3173611 to your computer and use it in GitHub Desktop.
#! /usr/bin/ruby
# Pre-commit hook for removing trailing whitespace, converting tabs to
# spaces and removing blank lines at the end of a file.
#
# Author: Clifton King <cliftonk@gmail.com>
# gist: https://gist.github.com/3173611
if File.exists? '.git/merge-rebase'
puts "Detected '.git/merge-rebase'! Skipping pre-commit hook..."
exit 0
end
diff_errors =
`git diff --staged --check HEAD`.each_line.reduce({}) do |memo, l|
if l =~ /\A([^\+\-][^:]+):(\d+): (.*)\.\Z/
file, line, message = $~[1..-1]
puts "pre-commit -> #{message} in '#{file}' on line #{line}"
memo[file] ||= []
memo[file] << line
end
memo
end
diff_errors.each do |file, lines|
puts "\nFixing #{file}..."
old_blob = `git rev-parse :0:#{file}`.strip
tabs = lines.map {|l| "#{l} s/\t/ /g" }.join ';'
trailing_whitespace = lines.map { |l| "#{l} s/[ \\t]*$//" }.join ';'
blank_eof_line = ":a -e '/^\\n*$/{$d;N;ba' -e '}'"
new_blob =
`git cat-file blob #{old_blob} |
sed -e '#{tabs}' \
-e '#{trailing_whitespace}' |
sed -e #{blank_eof_line} |
git hash-object -w --stdin`.strip
puts " old blob: #{old_blob}\n new blob: #{new_blob}"
new_entry = `git ls-files --stage "#{file}"`.strip.
sub(/ \w+ /, " #{new_blob} ")
`git diff #{old_blob} #{new_blob} | patch "#{file}"`
`echo "#{new_entry}" | git update-index --index-info`
end
if diff_errors.any?
puts "\nCorrected formatting errors in your commit!"
end
@jessedearing
Copy link

You can use #!/usr/bin/env ruby as the hashbang and that will account for whatever version of ruby they are using with RVM or Rbenv

@clifton
Copy link
Author

clifton commented Jul 25, 2012

Yeah I did that on purpose. We use REE on RVM and there's a spin-up time that's annoying with it, so I'm preferring system ruby

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