Skip to content

Instantly share code, notes, and snippets.

@jschaefer-workmatrix
Forked from mwise/README.md
Last active August 30, 2018 09:46
Show Gist options
  • Save jschaefer-workmatrix/0894da422ac6f6965812aea7255886ca to your computer and use it in GitHub Desktop.
Save jschaefer-workmatrix/0894da422ac6f6965812aea7255886ca to your computer and use it in GitHub Desktop.
Git hook to prevent merging staging branch into any other branch

To use this hook:

  • add the prepare-commit-msg file at .git/hooks/prepare-commit-msg and edit as needed
  • make it executable: chmod +x .git/hooks/prepare-commit-msg
  • disable fast-forward merges: git config branch.master.mergeoptions "--no-ff"
  • that's it!

NOTE: after a failed merge from a forbidden branch, the working tree will still be in a MERGING state. To discard the local working copy state, run: git reset --merge

If your trying to prevent merging into special branches have a look here https://gist.github.com/mwise/69ec35b646b52d98050d

#!/usr/bin/env ruby
# This git hook will prevent merging specific branches into any other branch
# Put this file in your local repo, in the .git/hooks folder
# and make sure it is executable.
# The name of the file *must* be "prepare-commit-msg" for Git to pick it up.
FORBIDDEN_BRANCHES = ["staging"]
def merge?
ARGV[1] == "merge"
end
def merge_msg
@msg ||= `cat .git/MERGE_MSG`
end
def from_branch
@from_branch = merge_msg.match(/Merge branch '(.*?)'/)[1]
end
def from_forbidden_branch?
FORBIDDEN_BRANCHES.include?(from_branch)
end
if merge? && from_forbidden_branch?
out = `git reset --merge`
puts
puts " STOP THE PRESSES!"
puts
puts " You are trying to merge #{from_branch} into the current branch."
puts " Surely you don't mean that?"
puts
puts " run the following command now to discard your working tree changes:"
puts
puts " git reset --merge"
puts
exit 1
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment