4

I have two branches, a production branch, and a master branch. I want to prevent merging into production any new branch that checked out from master and master itself.

There is a git pre hook that can help with that?

undefined
  • 6,366
  • 12
  • 46
  • 90

1 Answers1

0
  • create the prepare-commit-msg into your .git/hooks/ folder
  • make chmod permissions: chmod +x .git/hooks/prepare-commit-msg
  • disable fast-forward merges: git config branch.master.mergeoptions "--no-ff"

.git/hooks/prepare-commit-msg

#!/usr/bin/env ruby

# Only for exceptions. In your case is empty array
WHITELIST_BRANCH = ["hotfix"]

def merge?
  ARGV[1] == "merge"
end

def into_master?
  current_branch = `git branch | grep '*' | sed 's/* //'`.chop
  current_branch == "master"
end

def merge_msg
  @msg ||= `cat .git/MERGE_MSG`
end

def from_branch
  @from_branch = merge_msg.match(/Merge branch '(.*?)'/)[1]
end

def whitelist_branch?
  WHITELIST_BRANCH.include?(from_branch)
end

if merge? && into_master? && !whitelist_branch?
  out = `git reset --merge`
  puts
  puts " Fail #{from_branch} into the *master* branch "
  puts
  puts " run the following command now to discard your working tree changes:"
  puts
  puts " git reset --merge"
  puts
  exit 1
end

In this code only WHITELIST_BRANCH is available to merge

  • But why do we need the WHITELIST_BRANCH? I need to be able to merge to production branch any branch that doesn't check out from the master. – undefined Jul 22 '18 at 15:30
  • The WHITELIST_BRANCH is use for hotfix branch for example. In your case WHITELIST is a empty array. In this code use "dev" as whitelist really is not a good option. Fixed answer – Bráulio Figueiredo Jul 22 '18 at 17:42