Skip to content

Instantly share code, notes, and snippets.

@joshfreemanIO
Last active August 29, 2015 13:57
Show Gist options
  • Save joshfreemanIO/9795256 to your computer and use it in GitHub Desktop.
Save joshfreemanIO/9795256 to your computer and use it in GitHub Desktop.
Pre-Commit Hook for Git
#!/usr/bin/ruby
# https://www.ruby-forum.com/topic/122170#544763
git_files = `git diff --cached --name-only`.lines.map(&:chomp)
offending_lines = {}
def File.binary? name
open name do |f|
while (b=f.read(256)) do
return true if b[ "\0"]
end
end
false
end
git_files.each do |file|
next unless File.file?(file)
next if File.binary?(file)
File.open(file) do |f|
ln = 1
lna = Array.new
f.each_line do |line|
lna.push ln if line.match /\t/
offending_lines[file] = lna unless lna.empty?
ln += 1
end
f.close
end
end
eof_new_line = []
skip_newline = ['.css', '.min.js', '.map']
git_files.each do |file|
skip = false
skip_newline.each do |ext|
if File.basename(file) =~ /#{ext}$/
skip = true
end
end
next if skip == true
next unless File.file?(file)
next if File.binary?(file)
eof_new_line.push file unless IO.readlines(file).last.match /[^\n]\n$/
end
unless offending_lines.empty?
puts "\n"
puts " Pre-Commit Hook Failure (.git/hooks/pre-commit)"
puts " Tab characters are illegal in source control and Tabs were found in the following files"
puts "\n\n"
offending_lines.each do |file, line_numbers|
puts " #{file}"
line_numbers.each_slice(15).to_a.each { |sub_array| puts "\t" + sub_array.join(', ') }
puts "\n"
end
exit 1
end
unless eof_new_line.empty?
puts "\n"
puts " Pre-Commit Hook Failure (.git/hooks/pre-commit)"
puts " A single newline character (\\n) must be the last character for the following files:"
puts "\n\n"
eof_new_line.each do |file|
puts " #{file}"
puts "\n"
end
exit 1
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment