设置 Git Guardrails
设置一个 PreToolUse hook,在 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. 复制 hook 脚本
捆绑脚本位于:[scripts/block-dangerous-git.sh](scripts/block-dangerous-git.sh)
根据范围将其复制到目标位置:
- 项目:
.claude/hooks/block-dangerous-git.sh - 全局:
~/.claude/hooks/block-dangerous-git.sh
使用 chmod +x 使其可执行。
3. 将 hook 添加到设置
添加到相应的设置文件:
项目 (.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"
}
]
}
]
}
}
如果设置文件已存在,请将此 hook 合并到现有 hooks.PreToolUse 数组中。不要覆盖其他设置。
4. 询问自定义
询问用户是否希望从阻止列表中添加或移除任何模式。相应地编辑已复制的脚本。
5. 验证
运行快速测试:
echo '{"tool_input":{"command":"git push origin main"}}' | <path-to-script>
应以退出码 2 退出,并向 stderr 打印一条 BLOCKED 消息。