Search code examples
rubygitgithooksgit-push

Writing a pre-push hook in Git to grep all files for regex want to reject push if regex not found


I have the following pre-push hook. Ideally I would like it to go through all files that are being pushed to my repository and reject the push if the content of any of the files doesn't match the regular expression defined at the top. I'm getting the following error when attempting to loop through the files: "undefined method `each' for "":String (NoMethodError)". '.each' doesn't work as the git command is returning a string containing the changed files.

#!/usr/bin/env ruby

regex = "\\s*GO\\s*$"

localRef, remoteRef = ARGV
#puts localRef
#puts remoteRef

input = $stdin.readlines[0]
localSha = input.split(" ")[1]
remoteSha = input.split(" ")[3]
#puts localSha 
#puts remoteSha

range = "#{remoteSha}..#{localSha}"

#folderPath = `git rev-parse --show-toplevel`
#puts folderPath 

`git diff --name-only --diff-filter=ACMR #{range}`.each do |file|
  #puts file
  content = File.read(file)
  unless content.match(regex)
    puts "#{file} must end with 'GO' keyword"
    exit 1
  end
end

exit 0 

Does anyone have an idea of how I can loop through the files returned?

Thanks


Solution

  • Just needed to use ".each_line" instead of ".each".