ブランチ保護ガード
Pre-Tool入門Hookタイプ: pre-tool-use
ブランチ保護ガードは、すべてのファイル書き込み、編集、git commit操作をインターセプトし、現在のgitブランチが設定可能な保護ブランチリストに含まれていないか検証します。Claudeがmain、master、production、またはユーザーが指定したブランチでファイルを変更しようとすると、Hookがアクションをブロックし、先にfeatureブランチを作成するよう提案します。これにより、重要なブランチへの誤った直接commitを防止し、チームのブランチ戦略を強制します。
gitブランチ保護安全
Hookコード
#!/bin/bash
# Branch Protection Guard Hook
# Blocks writes and commits on protected branches
# Protected branches list (customize as needed)
PROTECTED_BRANCHES="main master production staging"
# Only check write/edit/bash operations
if [[ "$TOOL_NAME" != "Edit" ]] && [[ "$TOOL_NAME" != "Write" ]] && [[ "$TOOL_NAME" != "Bash" ]]; then
exit 0
fi
# For Bash, only check git commit/push commands
if [[ "$TOOL_NAME" == "Bash" ]]; then
if ! echo "$TOOL_INPUT" | grep -qE "git (commit|push|merge|rebase)"; then
exit 0
fi
fi
# Get current branch
CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD 2>/dev/null)
if [ -z "$CURRENT_BRANCH" ]; then
exit 0 # Not in a git repo, skip
fi
for BRANCH in $PROTECTED_BRANCHES; do
if [ "$CURRENT_BRANCH" = "$BRANCH" ]; then
echo "BLOCKED: Cannot modify files on protected branch '$BRANCH'."
echo "Please create a feature branch first:"
echo " git checkout -b feature/your-change"
exit 1
fi
done
exit 0
このHookをClaude Code設定または.claude/settings.jsonに追加して有効化してください。
実行プレビュー
ブランチ保護ガード
ブランチ保護ガードについて
Claude Code Hooksは、Claude操作中の特定イベントに応じてカスタムシェルコマンドを自動実行します。ブランチ保護ガードは入門レベルのPre-Tool Hookで、開発ワークフローの重要なタイミングでタスクを自動化し、手動ステップを削減してチーム全体の一貫性を維持します。