Back to Hooks
Branch Protection
PreToolUsePrevents direct file edits when on protected branches like main or production
gitbranchprotectionsafety
Hook Script
#!/bin/bash
# Branch Protection Hook
# Blocks direct edits on protected branches
PROTECTED_BRANCHES=("main" "master" "production" "staging")
CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD 2>/dev/null)
if [ -z "$CURRENT_BRANCH" ]; then
exit 0
fi
for branch in "${PROTECTED_BRANCHES[@]}"; do
if [ "$CURRENT_BRANCH" = "$branch" ]; then
echo "BLOCKED: You are on protected branch '$branch'."
echo "Please create a feature branch before making changes:"
echo " git checkout -b feature/your-change"
exit 1
fi
done
exit 0
Settings Configuration
{
"hooks": {
"PreToolUse": [
{
"matcher": "Edit|Write",
"command": "./hooks/branch-protect.sh"
}
]
}
}How to use
- Create a hooks directory in your project: mkdir hooks
- Save the hook script as hooks/branch-protect.sh
- Make it executable: chmod +x hooks/branch-protect.sh
- Add the configuration to your Claude Code settings
- Restart Claude Code to apply changes