Last active
March 29, 2019 22:33
-
-
Save medwig/3825b6ccb4489811b353edc29a2193e8 to your computer and use it in GitHub Desktop.
Git pre-push hook protect branch
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python3 | |
""" | |
Git pre-push hook: | |
Prevents pushing to protected branches | |
""" | |
import sys | |
PROTECTED_BRANCHES = ["develop", "master"] | |
def main(stdin): | |
"""Main function""" | |
remote_branch = parse_remote_branch(stdin) | |
if remote_branch in PROTECTED_BRANCHES: | |
print_warn(remote_branch) | |
sys.exit(1) | |
def parse_remote_branch(pre_push_stdin): | |
"""Returns the remote branch from Git pre-push stdin""" | |
pre_push_args = pre_push_stdin.split(" ") | |
try: | |
remote_ref = pre_push_args[2] | |
except IndexError: | |
return None | |
remote_branch = remote_ref.split("/")[-1] | |
return remote_branch | |
def print_warn(remote_branch): | |
"""Print a warning message""" | |
red = "\033[91m" | |
no_col = '\033[0m' | |
print(f"{red}No pushing to {remote_branch}! Open a pull request.{no_col}") | |
if __name__ == "__main__": | |
HOOK = sys.argv[0] | |
print("{0} hook triggered".format(HOOK)) | |
main(sys.stdin.readline()) | |
print("{0} hook passed".format(HOOK)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
$ cp pre-push .git/hooks/pre-push
$ chmod +x .git/hooks/pre-push