Created
July 25, 2012 00:27
-
-
Save clifton/3173611 to your computer and use it in GitHub Desktop.
This file contains 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/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 <[email protected]> | |
# 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 |
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
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