Skip to content

Instantly share code, notes, and snippets.

@threedaymonk
Created October 13, 2010 12:30
Show Gist options
  • Save threedaymonk/623932 to your computer and use it in GitHub Desktop.
Save threedaymonk/623932 to your computer and use it in GitHub Desktop.
Try and commit trailing spaces now, punk!
# Sneak in git commit hooks. Even if people don't run tests, they're likely to run this.
unless Rails.env == "production"
hook = "#{Rails.root}/.git/hooks/pre-commit"
script = <<'END'
#!/usr/bin/env ruby
#
# Reject commits that would introduce trailing spaces.
if system("git-rev-parse --verify HEAD >/dev/null 2>&1")
against = "HEAD"
else
# Initial commit: diff against an empty tree object
against = "4b825dc642cb6eb9a060e54bf8d69288fbee4904"
end
found = `git diff-index --check --cached #{against}`.
strip.
split(/\n/).
select{ |r| r !~ /^[+\-]/ }.
map{ |r| r[/^[^:]+/] }.
uniq
found.each do |path|
system "ruby -p -i'' -e '$_.sub!(/\s+$/, \"\")' \"#{path}\""
end
if found.any?
puts "There are trailing spaces in your commit. They have been fixed for"
puts "you, but you must add those fixes to the index (using git add) before you"
puts "can proceed."
exit 1
else
exit 0
end
END
unless File.exist?(hook) && File.read(hook) == script
File.open(hook, "w") do |f|
f << script
end
require "fileutils"
FileUtils.chmod 0755, hook
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment