Usa i PreToolUse Hooks per intercettare i comandi git in Bash e bloccare commit diretti al main, formati errati e operazioni pericolose.
Claude Code ha il permesso di eseguire git commit, git push e git checkout direttamente. Di solito è comodo, ma può portare a commit su main, messaggi in formato libero o force push inopportuni. Gli Hooks intercettano queste operazioni prima che avvengano.
#!/bin/bash
input=$(cat); cmd=$(echo "$input" | jq -r '.tool_input.command')
echo "$cmd" | grep -qE '^git (commit|push)' || exit 0
current_branch=$(git rev-parse --abbrev-ref HEAD 2>/dev/null)
if [[ "$current_branch" == "main" || "$current_branch" == "master" ]]; then
echo "I commit diretti su $current_branch non sono consentiti. Passa prima a un branch feature." >&2; exit 2
fi
#!/bin/bash
input=$(cat); cmd=$(echo "$input" | jq -r '.tool_input.command')
echo "$cmd" | grep -qE '^git commit' || exit 0
msg=$(echo "$cmd" | grep -oP '(?<=-m )["\x27].*?["\x27]' | tr -d '"'"'" || true)
[[ -z "$msg" ]] && exit 0
if ! echo "$msg" | grep -qE '^(feat|fix|docs|style|refactor|test|chore|perf|ci|build|revert)(\(.+\))?: .{3,}'; then
echo "Formato del messaggio di commit errato. Formato: <type>(<scope>): <description>" >&2; exit 2
fi
#!/bin/bash
input=$(cat); cmd=$(echo "$input" | jq -r '.tool_input.command')
if echo "$cmd" | grep -qE 'git push.*--force|git reset --hard|git push.*--delete'; then
if ! echo "$cmd" | grep -q '# ALLOW:'; then
echo "Operazione pericolosa bloccata. Aggiungi # ALLOW: <motivo> per continuare." >&2; exit 2
fi
fi
.claude/hooks/git-guard.sh:
#!/bin/bash
set -e
input=$(cat); cmd=$(echo "$input" | jq -r '.tool_input.command // empty')
[[ -z "$cmd" ]] && exit 0
echo "$cmd" | grep -q '^git' || exit 0
current_branch=$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo "unknown")
if echo "$cmd" | grep -qE '^git (commit|push)'; then
if [[ "$current_branch" == "main" || "$current_branch" == "master" ]]; then
echo "Su $current_branch — commit e push diretti bloccati. Passa a un branch feature." >&2; exit 2
fi
fi
if echo "$cmd" | grep -qE '^git commit.*-m'; then
msg=$(echo "$cmd" | grep -oP '(?<=-m )["\x27][^\x27"]*["\x27]' | tr -d '"'"'" || true)
if [[ -n "$msg" ]] && ! echo "$msg" | grep -qE '^(feat|fix|docs|style|refactor|test|chore|perf|ci|build|revert)(\(.+\))?: .{3,}'; then
echo "Formato errato. Formato: <type>(<scope>): <description>" >&2; exit 2
fi
fi
if echo "$cmd" | grep -qE 'git push.*--force|git reset --hard|git push.*--delete'; then
if ! echo "$cmd" | grep -q '# ALLOW:'; then
echo "Operazione pericolosa bloccata. Aggiungi # ALLOW: <motivo>." >&2; exit 2
fi
fi
PreToolUse + matcher Bash + rilevamento comandi git. Tre regole prioritarie: bloccare commit su main, validare il formato dei messaggi, intercettare force push e reset --hard.