Back to Hooks

Branch Protection

PreToolUse

Prevents 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

  1. Create a hooks directory in your project: mkdir hooks
  2. Save the hook script as hooks/branch-protect.sh
  3. Make it executable: chmod +x hooks/branch-protect.sh
  4. Add the configuration to your Claude Code settings
  5. Restart Claude Code to apply changes