跳到正文
DEV Community· Vildanden·· 4 小時前AI 評分61

如何阻止 Claude Code 透過 --no-verify 跳過 Git hooks

Stop Claude Code from skipping git hooks with --no-verify

AI 導讀

作者提供一個 Claude Code 的 PreToolUse hook,阻止 `git commit` 使用 `--no-verify` 或 `-n`,避免提交命令跳過 Git hooks。

正文

Vildanden

A PreToolUse hook can already block git push --force and git reset --hard. That still leaves a hole: git commit --no-verify (or -n) skips the hook that would have caught a secret, a red test, or a broken lint. A small PreToolUse hook can refuse that flag so the repo hooks still run.

The hook should name the blocked command and exit 2.

The hook

Save this as .claude/hooks/block_no_verify.py and make it executable:

#!/usr/bin/env python3
import json
import re
import sys

try:
    event = json.load(sys.stdin)
except json.JSONDecodeError:
    sys.exit(0)

tool = event.get("tool_name") or event.get("tool") or ""
inp = event.get("tool_input") or event.get("input") or {}
if tool != "Bash":
    sys.exit(0)

command = str(inp.get("command") or "")
if not re.search(r"\bgit\b", command) or not re.search(r"\b(commit|commit-tree)\b", command):
    sys.exit(0)

if re.search(r"(^|[\s])--no-verify(\s|=|$)", command):
    print("PreToolUse: blocked git commit --no-verify. Let the repo hooks run.")
    sys.exit(2)

for token in re.findall(r"(?:[^\s\"']+|\"[^\"]*\"|'[^']*')", command):
    if token.startswith("'") or token.startswith('"') or token.startswith("--"):
        continue
    if token.startswith("-") and "n" in token[1:]:
        print("PreToolUse: blocked git commit -n. Let the repo hooks run.")
        sys.exit(2)

Wire it in .claude/settings.json under PreToolUse with command set to python3 .claude/hooks/block_no_verify.py. If your settings support a matcher, limit it to Bash.

Why this beats a pasted prompt

"Don't skip hooks" in CLAUDE.md only works when the model remembers it mid-turn. After a hook fails, the next move is often git commit --no-verify to "just land the change." The PreToolUse hook runs before the shell, so that escape hatch is closed. If a hook is actually broken, fix the hook or run the commit yourself in a terminal — do not let the agent skip it.

Tips

  • Keep the hook local, fast, and free of network calls.
  • Pair it with the force-push / reset --hard PreToolUse guard so destructive git and hook-skipping are both blocked.
  • Short -n is treated as --no-verify on git commit. Quoted commit messages are ignored, so git commit -m "do not verify" will not trip the hook.

Want the rest of the setup?

I keep copy-ready Claude Code configs (CLAUDE.md templates, slash commands, hooks, permission rules) in Vildanden Agent Config. There's a free sample: https://justly-mia-429.rehost.page/

來源:DEV Community · dev.to