B

Block Push to Main Hook

Prevents Claude from pushing directly to main or master branches. Enforces a pull-request-based workflow by intercepting git push commands and blocking those targeting protected branches. A must-have for team environments.

HookCommunitygit workflowv1.0.0MIT
0 views0 copies

Hook Type

PreToolUse with Bash matcher -- Intercepts git push commands before execution.

Description

This hook enforces branch protection by preventing direct pushes to main and master branches. It intercepts all Bash commands, detects git push operations, and blocks those targeting protected branches. This ensures all changes go through pull requests for proper review.

Patterns/Rules

  • Blocks git push origin main, git push origin master
  • Blocks git push --force to any protected branch
  • Also catches shorthand like git push when on main/master branch
  • Does NOT block pushes to feature branches
  • Exit code 2 blocks the command; exit code 0 allows it

Configuration

Hook Script (scripts/block-push-to-main.sh)

#!/bin/bash # block-push-to-main.sh -- Prevent direct pushes to protected branches INPUT=$(cat) CMD=$(echo "$INPUT" | jq -r '.tool_input.command') # Only check git push commands if ! echo "$CMD" | grep -q "git push"; then exit 0 fi # Protected branch names PROTECTED_BRANCHES=("main" "master" "production" "release") # Check if pushing to a protected branch for branch in "${PROTECTED_BRANCHES[@]}"; do # Match explicit branch in push command if echo "$CMD" | grep -qE "git push.*\b${branch}\b"; then echo "BLOCKED: Direct push to '$branch' is not allowed." >&2 echo "Please create a feature branch and open a pull request instead." >&2 echo " git checkout -b feat/your-feature" >&2 echo " git push -u origin feat/your-feature" >&2 echo " gh pr create" >&2 exit 2 fi done # Check if current branch is protected (for plain 'git push') CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD 2>/dev/null) for branch in "${PROTECTED_BRANCHES[@]}"; do if [ "$CURRENT_BRANCH" = "$branch" ] && echo "$CMD" | grep -qE "^git push( |$)"; then echo "BLOCKED: You are on '$branch'. Direct push is not allowed." >&2 echo "Please create a feature branch first." >&2 exit 2 fi done exit 0

Settings Configuration

{ "hooks": { "PreToolUse": [ { "matcher": "Bash", "hooks": [ { "type": "command", "command": "bash ./scripts/block-push-to-main.sh" } ] } ] } }

Action

Before any Bash command:

  1. Checks if the command contains git push
  2. If yes, checks if the target branch is protected
  3. Also checks the current branch for plain git push commands
  4. If a protected branch push is detected: blocks with a helpful message showing the correct workflow
  5. Feature branch pushes proceed normally
Community

Reviews

Write a review

No reviews yet. Be the first to review this template!

Similar Templates