Skip to content

Instantly share code, notes, and snippets.

@withakay
Created January 29, 2024 12:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save withakay/2314d35ce44e9f9f92b80f8ff8014c89 to your computer and use it in GitHub Desktop.
Save withakay/2314d35ce44e9f9f92b80f8ff8014c89 to your computer and use it in GitHub Desktop.
pre-commit_commit-to-main-guard.sh
#!/bin/bash
# Setup:
# Assuming you don't alread have a global githooks dir
#
# mkdir -p ~/.githooks/
#
# Save this script to the above path.
# Make a shell script called `pre-commit` in the above path (touch ~/.githooks/pre-commit).
# Edit pre-commit script sp it calls this script from it e.g.
#
# ``` pre-commit
# #!/bin/bash
# bash ~/.githooks/pre-commit_commit-to-main-guard.sh
# ```
#
# Configure git
#
# git config --global core.hooksPath ~/.githooks
protected_branches=("master" "main")
current_branch="$(git rev-parse --abbrev-ref HEAD 2>/dev/null)"
# Check if git command is available and if we are in a git repository
if [ $? -ne 0 ]; then
echo "Error: git command failed or not in a git repository."
exit 1
fi
# Check if the current branch is a protected branch
if echo "${protected_branches[@]}" | grep -wq "$current_branch"; then
echo "You are about to commit to $current_branch. Are you sure? [y/n]"
read -p "" -n 1 -r yn
echo
if [[ ! $yn =~ ^[Yy]$ ]]; then
echo "Commit aborted."
exit 1
fi
else
# Not a protected branch, proceed normally
exit 0
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment