Skip to content

Instantly share code, notes, and snippets.

@mayrmt
Last active April 13, 2023 06:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mayrmt/b07d9ad92f53bf34f20dc34e4c9b36a6 to your computer and use it in GitHub Desktop.
Save mayrmt/b07d9ad92f53bf34f20dc34e4c9b36a6 to your computer and use it in GitHub Desktop.
Pre-commit hook to enforce use of feature branches and reject commits to master
#!/bin/bash
# This pre-commit hook prevents commits on branch '<forbidden_branch>' and enforces the use of feature branches.
# To use it in your repository, follow these steps:
# 1. Copy this file to `.git/hooks/pre-commit`
# 2. Make the file executable, e.g. via `chmod u+x .git/hooks/pre-commit`
#
# If one wants to commit to the '<forbidden_branch>' branch, the commit is rejected (script exits 1).
# The user is asked to create and checkout a new feature branch in order to proceed with the commit.
#
# The commit will be accepted if the script exits with 0
#
# Specify name of the forbidden branch inside quotes
forbidden_branch="develop"
### Prevent commits to '<forbidden_branch>' ####################
branch="$(git rev-parse --abbrev-ref HEAD)"
if [ "$branch" == $forbidden_branch ]
then
printf "\n"
echo "Committing directly to branch '$forbidden_branch' is not allowed!"
printf "\n"
echo "--> Create and checkout a new feature branch via:"
echo "git checkout -b <branchName>"
echo "(All staged and unstaged changes are kept)"
printf "\n"
echo "--> Afterwards, commit on the newly created branch."
printf "\n"
exit 1
fi
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment