設定 Git 護欄
建立一個 PreToolUse 鉤子,在 Claude 執行危險的 git 指令前進行攔截並阻止。
被封鎖的項目
git push(所有變體,包含--force)git reset --hardgit clean -f/git clean -fdgit branch -Dgit checkout ./git restore .
當被封鎖時,Claude 會看到一則訊息,告知它沒有權限存取這些指令。
步驟
1. 詢問範圍
詢問使用者:為僅此專案(.claude/settings.json)還是所有專案(~/.claude/settings.json)安裝?
2. 複製鉤子腳本
隨附的腳本位於:scripts/block-dangerous-git.sh
根據範圍將其複製到目標位置:
- 專案:
.claude/hooks/block-dangerous-git.sh - 全域:
~/.claude/hooks/block-dangerous-git.sh
使用 chmod +x 設為可執行。
3. 將鉤子加入設定
加到對應的設定檔中:
專案(.claude/settings.json):
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/block-dangerous-git.sh"
}
]
}
]
}
}
全域(~/.claude/settings.json):
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "~/.claude/hooks/block-dangerous-git.sh"
}
]
}
]
}
}
如果設定檔已存在,請將鉤子合併至現有的 hooks.PreToolUse 陣列中 — 不要覆蓋其他設定。
4. 詢問自訂設定
詢問使用者是否要從封鎖清單中新增或移除任何模式。據此編輯已複製的腳本。
5. 驗證
執行快速測試:
echo '{"tool_input":{"command":"git push origin main"}}' | <path-to-script>
應會以退出碼 2 結束,並在 stderr 中印出 BLOCKED 訊息。