#!/usr/bin/python
##
# Author: Nicolas Martinez V. <mailto:nmartinezv@icloud.com>
# Description: Git Hook (server-side) allowing to prevent merge from some branches to anothers
# based on the hook created by Bertrand Benoit <mailto:contact@bertrand-benoit.net>
## Version: 0.9

import sys
import subprocess
import re

class branches:
  def __init__(self, origin, destination):
    self.origin = origin
    self.destination = destination

  def getOrigin(self):
    return self.origin

  def getDestination(self):
    return self.destination

branchesList = []

# add branches here
branchesList.append(branches('develop', 'testing'))
branchesList.append(branches('testing', 'master'))

# Considers only merge commit.
if not (len(sys.argv) >= 2 and sys.argv[2] == 'merge'):
  sys.exit(0)

with open(sys.argv[1], 'r') as f:
  mergeMessage = f.readline()
mergeBranchExtract = re.compile("Merge branch '([^']*)'.*$").search(mergeMessage)

if not mergeBranchExtract:
  print('Unable to extract branch to merge from message: ', mergeMessage)
  sys.exit(0)  # Ensures normal merge as failback

mergeBranch = mergeBranchExtract.group(1)

currentBranchFullName = subprocess.check_output(['git', 'symbolic-ref', 'HEAD'])
currentBranchExtract = re.compile("^.*/([^/]*)\n$").search(currentBranchFullName)

if not currentBranchExtract:
    print('Unable to extract current branch from: ', currentBranchFullName)
    sys.exit(1)  # Ensures normal merge as failback

currentBranch = currentBranchExtract.group(1)

for item in branchesList:
  if currentBranch == item.getDestination() and mergeBranch != item.getOrigin():
    print(
      "FORBIDDEN: Merging from '",
      mergeBranch,
      "' to '",
      currentBranch,
      "' is NOT allowed. Contact your administrator.",
      "Now, you should use git merge --abort and keep on your work.")
    sys.exit(1)  # This is exactly the situation which is forbidden
sys.exit(0)