Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@nhunzaker
Created May 29, 2012 19:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nhunzaker/2830256 to your computer and use it in GitHub Desktop.
Save nhunzaker/2830256 to your computer and use it in GitHub Desktop.
My FED Pre-Commit Hook
#!/usr/bin/env ruby
errors = false
# Create a simple line break
puts ""
# Now let's get a list of the changed files that have been staged
changed_files = `git diff --staged --name-only HEAD`.split("\n")
# A list of validators, and their associated behaviors
validators = {
:js => {
:label => "javascript",
:app => "jshint",
:supported => !`type jshint`.include?("not found"),
:output => Proc.new { |file| `jshint #{file}` },
:valid => Proc.new { |file| output.empty? }
},
:css => {
:label => "css",
:app => "csslint",
:supported => !`type csslint`.include?("not found"),
:output => Proc.new { |file| `csslint #{file}`.strip},
:valid => Proc.new { |output| output == "csslint: No errors in #{file}." }
},
:erb => {
:label => "erb",
:app => "rails-erb-check",
:supported => !`type rails-erb-check`.include?("not found"),
:output => Proc.new { |file| `rails-erb-check #{file}`.strip },
:valid => Proc.new { |output| output.include?("valid") }
},
:scss => {
:label => "scss",
:app => "sass",
:supported => !`type sass`.include?("not found"),
:output => Proc.new { |file| `sass --check #{file} 2>&1` },
:valid => Proc.new { |output| output.include?("Invalid CSS") == false }
}
}
# For each file, if we have a validator for it, run it
changed_files.each do |file|
type = validators[file.split(".").last.to_sym]
next if type.nil?
print "Validating #{file}... "
# Notify the user if they need to install a validator
if not type[:supported]
puts "\033[31mPlease install #{type[:app]} for #{type[:label]} validation support.\033[0m"
next
end
output = type[:output].call(file)
valid = type[:valid].call(output)
if not valid
errors = true
puts "\033[31merrors in #{type[:label]}.\033[0m" + "\n" + output
else
puts "\033[32m#{type[:label]} is valid\033[0m"
end
end
# Conclusion:
if errors
puts "\n\033[31mErrors found in front-end code, preventing commit :(\033[0m"
exit!
else
puts "\033[32m\nFrontend code appears to be clean :)\n\033[0m"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment