Git Guardrails Claude Code

作者 vinvcnbf98e53f9208無授權條款4.6K 個星標收錄於 2026年10月8日更新於 2026年10月8日儲存庫今天更新

设置 Claude Code hooks,在危险 git commands(push、reset --hard、clean、branch -D 等)执行前阻止它们。适用于用户想防止破坏性 git 操作、添加 git safety hooks,或在 Claude Code 中阻止 git push/reset 时。

AI 產生的概覽

安裝 Claude Code 的 PreToolUse hook,用來阻擋 push、reset --hard、clean 等危險 git 指令。

功能
引導使用者把隨附的 shell 指令碼安裝成 Claude Code 的 PreToolUse hook,可選擇只對目前專案或對所有專案生效。它會複製指令碼、加上可執行權限,並把 hook 設定合併到對應的 settings 檔案中,而不會覆蓋既有設定。這個 hook 會攔截 Bash 工具呼叫,對被阻擋的 git 指令以結束碼 2 結束,讓 Claude 看到無權存取這些指令的訊息。
適用情境
當你想避免 Claude Code 執行破壞性 git 操作時使用。適合用於要求加入 git 安全 hook、阻擋 git push 或 reset,或在單一專案或所有專案中限制危險指令的情境。
執行需求
需要支援 hook 的 Claude Code、shell 環境,以及對專案 .claude 目錄或使用者家目錄下 .claude 目錄的寫入權限。此技能附有可執行指令碼(scripts/block-dangerous-git.sh),需要 chmod 與修改 settings 檔案;不需要憑證或網路存取。

设置 Git Guardrails

设置一个 PreToolUse hook,在 Claude 执行危险 git commands 前拦截并阻止它们。

会被阻止的命令

  • git push(包括 --force 在内的所有 variants)
  • git reset --hard
  • git clean -f / git clean -fd
  • git branch -D
  • git checkout . / git restore .

被阻止时,Claude 会看到一条 message,说明它无权访问这些 commands。

步骤

1. 询问安装范围

询问用户:只为当前 project 安装(.claude/settings.json),还是为所有 projects 安装(~/.claude/settings.json)?

2. 复制 hook 脚本

bundled script 位于:scripts/block-dangerous-git.sh [blocked]

根据 scope 复制到目标位置:

  • Project: .claude/hooks/block-dangerous-git.sh
  • Global: ~/.claude/hooks/block-dangerous-git.sh

用 chmod +x 让它可执行。

3. 把 hook 加入 settings

添加到对应 settings file:

Project (.claude/settings.json):

json
{  "hooks": {    "PreToolUse": [      {        "matcher": "Bash",        "hooks": [          {            "type": "command",            "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/block-dangerous-git.sh"          }        ]      }    ]  }}

Global (~/.claude/settings.json):

json
{  "hooks": {    "PreToolUse": [      {        "matcher": "Bash",        "hooks": [          {            "type": "command",            "command": "~/.claude/hooks/block-dangerous-git.sh"          }        ]      }    ]  }}

如果 settings file 已存在,把 hook merge 到现有 hooks.PreToolUse array 中,不要覆盖其他 settings。

4. 询问是否定制

询问用户是否要在 blocked list 中添加或移除 patterns。相应编辑复制后的 script。

5. 验证

运行快速测试:

bash
echo '{"tool_input":{"command":"git push origin main"}}' | <path-to-script>

应以 code 2 退出,并向 stderr 打印 BLOCKED message。

來源與署名

來源:vinvcn/mattpocock-skills-zh-cn位於skills/misc/git-guardrails-claude-code提交bf98e53

授權條款: 無授權條款

內容歸原作者所有。SourceWeft 從公開儲存庫中收錄這些內容。

檢舉或申請下架