Skip to content

Instantly share code, notes, and snippets.

@jeffyip
Created April 18, 2012 21:23
Show Gist options
  • Save jeffyip/2416675 to your computer and use it in GitHub Desktop.
Save jeffyip/2416675 to your computer and use it in GitHub Desktop.
A Script to Check the Syntax of Ruby Files -- Based off of a git precommit hook
#!/usr/bin/env ruby
require 'open3'
include Open3
skip_erb_files = true
compiler_ruby = `which rbx`.strip
compiler_ruby = `which ruby`.strip if compiler_ruby.length == 0
all_files = Dir["./**/**"]
changed_ruby_files = []
all_files.each do |file|
changed_ruby_files << file if file =~ /(.+\.(e?rb|task|rake|thor)|[Rr]akefile|[Tt]horfile)/
end
problematic_files = changed_ruby_files.inject([]) do |problematic_files, file|
if File.readable? file
puts "checking #{file}"
cmd = if file =~ /\.erb\z/
# Set trim mode to "-", just as Rails does
"erb -xT - #{file} | #{compiler_ruby} -wc" unless skip_erb_files
else
"#{compiler_ruby} -wc #{file}"
end
unless cmd.nil? then
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
unless errors.empty?
errors.map!{ |line| line.sub(/#{file}:/, '') }
problematic_files << "#{file}:\n#{errors.join("\n")}"
end
end
end
problematic_files
end
if problematic_files.size > 0
$stderr.puts problematic_files.join("\n\n")
exit 1
else
# All is well
exit 0
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment