Skip to content

Instantly share code, notes, and snippets.

@jaredhoyt
Last active December 24, 2015 22:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jaredhoyt/6875149 to your computer and use it in GitHub Desktop.
Save jaredhoyt/6875149 to your computer and use it in GitHub Desktop.
git pre-push hook to prevent force push to master
#!/usr/bin/env ruby
# This script has been slightly adapted from:
# http://blog.bigbinary.com/2013/09/19/do-not-allow-force-pusht-to-master.html
class PrePushHandler
def handle
reject if force_pushing? && pushing_to_master?
end
private
def current_command
@current_command ||= `ps -ocommand= -p #{Process.ppid}`
end
def force_pushing?
current_command.match(/--force|-f/)
end
def pushing_to_master?
current_branch == 'master' || current_command.match('master')
end
def current_branch
result = %x{git branch}.split("\n")
if result.empty?
feedback "It seems your app is not a git repository."
else
result.select { |b| b =~ /^\*/ }.first.split(" ").last.strip
end
end
def reject
messages = ["Your attempt to FORCE PUSH to MASTER has been rejected."]
messages << "If you still want to FORCE PUSH then you need to ignore the pre_push git hook by
executing following command."
messages << "git push master --force --no-verify"
feedback messages
end
def feedback(messages)
puts "*" * 40
[messages].flatten.each do |message|
puts message
end
puts "*" * 40
exit 1
end
end
PrePushHandler.new.handle
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment