Skip to content

Instantly share code, notes, and snippets.

@itsterry
Forked from vindia/pre-commit.rb
Created October 1, 2015 22:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save itsterry/725f5825a7c032387983 to your computer and use it in GitHub Desktop.
Save itsterry/725f5825a7c032387983 to your computer and use it in GitHub Desktop.
Git pre-commit hook to block committing Spec files with :focus => true on test blocks and .orig files from merge conflicts
#!/usr/bin/env ruby
orig_hits = []
spec_hits = []
# In Mountion Lion Apple uses BSD grep with REG_ENHANCED enabled,
# so all regular regex special chars like ?, | and + need to be
# escaped...
def grep_focus
if `grep --v`.match /BSD/
'grep "\(:focus\(\s\?=>\s\?true\)\?\|focus:\s\?true\)"'
else
'grep -P "(:focus(\s?=>\s?true)?|focus:\s?true)"'
end
end
# Find the names of all files that have been (A)dded (C)opied or (M)odified
filenames = `git diff --cached --name-only --diff-filter=ACM`.split("\n")
filenames.each do |filename|
# Perform special checks for _spec filenames (rspec tests)
if filename.match /_spec\.rb$/
# Filter all the additions to this file, find if they contain `focus: true`
# or `:focus => true` and store them without the initial `+` and spaces
results = `git diff --cached #{filename} | grep "^\+[^+]" | #{grep_focus}`.split("\n").map do |r|
r.sub(/^\+[\s\t]*/, '')
end
if $? == 0
# Add the relevant change with line number to the spec_hits array
results.each do |r|
spec_hits.push "#{filename}:" + `grep -n "#{r}" #{filename}`.sub(/:\s+/, ' ').chomp
end
end
# Perform special checks for .orig filenames (from merge conflicts)
elsif filename.match /\.orig$/
orig_hits.push filename
end
end
if spec_hits.any?
puts "\e[33m>>> Please remove your `focus: true` from the following tests before committing\e[0m"
puts spec_hits.join("\n")
end
if orig_hits.any?
puts "\e[33m>>> You should not add merge conflict filenames, like these:\e[0m"
puts orig_hits.join("\n")
end
exit 1 if spec_hits.any? || orig_hits.any?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment