Created
November 7, 2014 14:29
-
-
Save fuzzygroup/24fe19dda82a9d8c188f to your computer and use it in GitHub Desktop.
my lint based, error checking pre-commit
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/env ruby | |
# | |
# A hook script to verify that only syntactically valid ruby code is commited. | |
# Called by git-commit with no arguments. The hook should | |
# exit with non-zero status after issuing an appropriate message if | |
# it wants to stop the commit. | |
# | |
# Put this code into a file called "pre-commit" inside your .git/hooks | |
# directory, and make sure it is executable ("chmod +x .git/hooks/pre-commit") | |
puts "in .git/hooks/pre-commit" | |
require 'open3' | |
include Open3 | |
# Set this to true if you want warnings to stop your commit | |
stop_on_warnings = false | |
stop_on_errors = true | |
# compiler_ruby = `which rbx`.strip | |
# compiler_ruby = `which ruby`.strip if compiler_ruby.length == 0 | |
# setting compiler to ruby-1.9.3 since `which ruby` was setting it to 1.8.7 | |
compiler_ruby = "$HOME/.rvm/rubies/ruby-1.9.3-p484/bin/ruby" | |
changed_ruby_files = `git diff-index --name-only --cached HEAD`.split("\n").inject([]) do |files, line| | |
files << line.chomp if line =~ /(.+\.(e?rb|task|rake|thor)|[Rr]akefile|[Tt]horfile)/ | |
files | |
end | |
problematic_files = changed_ruby_files.inject([]) do |problematic_files, file| | |
if File.readable? file | |
cmd = if file =~ /\.erb\z/ | |
# Set trim mode to "-", just as Rails does | |
# Replacing all <%= tags with <% for the syntax check | |
"sed 's/<%=/<%/g' #{file} | erb -xT - | #{compiler_ruby} -wc" | |
else | |
"#{compiler_ruby} -wc #{file}" | |
end | |
errors = nil | |
popen3(cmd) do |stdin, stdout, stderr| | |
errors = stderr.read.split("\n") | |
end | |
errors.reject!{ |line| line =~ /[0-9]+:\s+warning:/ } unless stop_on_warnings | |
errors.reject!{ |line| line =~ /[0-9]+:\s+syntax error/ } unless stop_on_errors | |
unless errors.empty? | |
errors.map!{ |line| line.sub(/#{file}:/, '') } | |
problematic_files << "#{file}:\n#{errors.join("\n")}" | |
end | |
end | |
problematic_files | |
end | |
if problematic_files.size > 0 | |
$stderr.puts problematic_files.join("\n\n") | |
exit 1 | |
else | |
puts "no syntax errors" | |
# All is well | |
exit 0 | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment