Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #! /usr/bin/python2.7
- import sys
- import fileinput
- import subprocess
- class RejectError(Exception):
- code = 255
- msg = ""
- def reject(self):
- if self.msg:
- sys.stdout.write(self.msg)
- sys.exit(self.code)
- class ProtectMasterBranchError(RejectError):
- code = 1
- msg = "branch master is protected, no one can delete or force push"
- class Git(object):
- @staticmethod
- def is_null_commit(commit_id):
- return True if commit_id == '0' * len(commit_id) else False
- @staticmethod
- def is_force_push(old_commit_id, new_commit_id):
- merge_base = subprocess.check_output(
- "git merge-base %s %s" % (old_commit_id, new_commit_id),
- shell=True,
- )
- return old_commit_id != merge_base
- def protect_master_branch(ref, old_commit_id, new_commit_id):
- if ref != 'refs/heads/master':
- return
- if Git.is_null_commit(old_commit_id):
- return
- if Git.is_null_commit(new_commit_id):
- raise ProtectMasterBranchError()
- if Git.is_force_push(old_commit_id, new_commit_id):
- raise ProtectMasterBranchError()
- def main():
- try:
- for line in fileinput.input():
- old_commit_id, new_commit_id, ref = line.split()
- protect_master_branch(ref, old_commit_id, new_commit_id)
- except RejectError as error:
- error.reject()
- main()
Add Comment
Please, Sign In to add comment