2

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

user5754
  • 147
  • 1
  • 7
  • This appears to be a question about Ruby programming, not about Git itself. If so, none of the tags that are on it (git, githooks, git-push) are really correct and the right ones would be Ruby-related. – torek May 30 '17 at 14:35
  • Yeah, you're right. I've added the ruby tag. – user5754 May 30 '17 at 22:46
  • this does not work when pushing new branches (nor with --delete) – ricab Feb 01 '19 at 13:03
  • You are correct @ricab, the git command was eventually refactored to use the reflog. Works well now except the odd occurrence of pulling in unwanted files after a rebase. I also explicitly ignore deletes. – user5754 Feb 04 '19 at 03:38
  • Thanks, perhaps you want to share the way you accomplished that in https://stackoverflow.com/questions/54480609/git-pre-push-hook-to-reject-string-in-overall-changes ? – ricab Feb 04 '19 at 10:32
  • Hope it works for you @ricab – user5754 Feb 04 '19 at 21:37

1 Answers1

1

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

user5754
  • 147
  • 1
  • 7