Skip to content

Instantly share code, notes, and snippets.

@themakunga
Last active March 23, 2021 19:56
Show Gist options
  • Save themakunga/1ba3d397594d5f3fa298c547c14c82e2 to your computer and use it in GitHub Desktop.
Save themakunga/1ba3d397594d5f3fa298c547c14c82e2 to your computer and use it in GitHub Desktop.

Limit commit branches

In your git project download the script, change the name, made it executable and you can use it

wget https://gist.githubusercontent.com/themakunga/1ba3d397594d5f3fa298c547c14c82e2/raw/65b4a81eaef5ba30063f6f2954e3c87da11bd84d/prepare-commit-msg.py

mv ./prepare-commit-msg.py ./.git/hooks/prepare-commit-msg

chmod a+x ./.git/hooks/prepare-commit-msg
#!/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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment