| name | git-guardrails-claude-code |
| description | 为 Claude Code 配置 hooks,在 push、reset --hard、clean、branch -D 等危险 Git 命令执行前将其拦截。适用于用户希望防止破坏性 Git 操作、添加 Git 安全 hooks,或禁止 Claude Code 执行 git push/reset 的场景。 |
配置 Git Guardrails
配置一个 PreToolUse hook,在 Claude 执行危险 Git 命令前进行拦截。
会被阻止的命令
git push(包括 --force 在内的所有变体)
git reset --hard
git clean -f / git clean -fd
git branch -D
git checkout . / git restore .
命令被阻止后,Claude 会收到一条消息,说明它无权执行这些命令。
步骤
1. 询问安装范围
询问用户:只为当前项目安装(.claude/settings.json),还是为所有项目安装(~/.claude/settings.json)?
2. 复制 hook 脚本
仓库内置的脚本位于:scripts/block-dangerous-git.sh
根据安装范围,把它复制到对应位置:
- 项目级:
.claude/hooks/block-dangerous-git.sh
- 全局:
~/.claude/hooks/block-dangerous-git.sh
执行 chmod +x,为脚本添加可执行权限。
3. 在 settings 中添加 hook
将配置写入对应的 settings 文件。
项目级(.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"
}
]
}
]
}
}
settings 文件已经存在时,把 hook 合并到现有的 hooks.PreToolUse 数组中,不要覆盖其他配置。
4. 询问是否需要自定义
询问用户是否要在阻止清单中增加或移除命令模式。根据用户的选择修改复制后的脚本。
5. 验证
运行一次快速测试:
echo '{"tool_input":{"command":"git push origin main"}}' | <path-to-script>
脚本应以状态码 2 退出,并向 stderr 输出 BLOCKED 消息。