Skip to content

Instantly share code, notes, and snippets.

@rahulramfort
Created August 19, 2020 16:02
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rahulramfort/381ee3309e7688d7ed98b6c23ccc2f16 to your computer and use it in GitHub Desktop.
Save rahulramfort/381ee3309e7688d7ed98b6c23ccc2f16 to your computer and use it in GitHub Desktop.
Pre-commit hook - Validate Syntax for Ruby files
#!/usr/bin/env ruby
=begin
A hook to make sure that all staged .rb files are syntatically correct.
The hook tries to run `ruby -c file_path` for all those files and
prints outs the errors if any and halts the commit.
If you want to use this pre-commit, simply copy the code and create a
file called 'pre-commit' inside your .git/hooks directory.
Ensure to make file executable as well `chmod +x .git/hooks/pre-commit`
=end
# SyntaxChecker validates the syntax of all files
class SyntaxChecker
require 'open3'
PASS_MSG = 'pre-commit - ruby syntax check passed'.freeze
FAIL_MSG = 'pre-commit - ruby syntax check failed'.freeze
class << self
def perform
staged_files = `git diff --name-only --staged`
staged_ruby_files = staged_files.split("\n")
pick_rb_files(staged_ruby_files)
return if staged_ruby_files.empty?
errors = run_syntax_check(staged_ruby_files)
return p PASS_MSG if errors.empty?
p FAIL_MSG, errors and exit 1
end
private
def pick_rb_files(files)
files.select! { |f| f[-3] == '.' && f[-2] == 'r' && f[-1] == 'b' }
end
def run_syntax_check(files)
errors = ''
files.each do |file_path|
cmd = "ruby -c #{file_path}"
Open3.popen3(cmd) do |_in, _out, err|
err_text = err.read.to_s
errors += err_text unless err_text.empty?
end
end
errors
end
end
end
SyntaxChecker.perform
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment