git-guardrails-claude-code
БесплатноБез исполняемых скриптовНе проверенInstalls a Claude Code PreToolUse hook that stops destructive git commands before the shell runs them: force pushes, pushes to protected branches, reset…
от TerminalSkills★ 221 звезда на GitHubОб этом скилле
Git Guardrails for Claude Code
Overview
Claude Code fires a PreToolUse hook before every tool call and hands it the call as JSON on stdin; for the Bash tool the command line is in tool_input.command. This skill installs one Python script on that event. It tokenizes the command the way a shell would, finds the git invocations in it, and answers in one of three ways: stay silent (the normal permission flow continues), return permissionDecision: "ask" (the user gets a prompt, even in auto mode), or exit with code 2 (the call is cancelled and Claude reads the reason from stderr). A hook block holds in every permission mode, bypassPermissions included.
A plain deny rule such as Bash(git push *) is not enough on its own: Claude Code's documentation lists git -C . push, git -c push.default=current push and git 'push' as spellings such a rule does not stop, and a command wrapped in sh -c '...' slips past it too. The script handles all of these. It is still a seatbelt for an honest agent, not a security boundary.
Instructions
1. Agree on the policy
Ask three things: where to install, which branches are protected, and what an ordinary push should do. The defaults:
| Command | Outcome | Reason |
|---|---|---|
push --force, -f, +refspec, --mirror |
block | overwrites commits on the remote |
push whose target is a protected branch, named or implied by HEAD |
block | publishing there is the user's call |
any other push; --force-with-lease, --delete, :branch, --all, --tags |
ask | visible to others, sometimes wanted |
reset --hard, clean -f, checkout -- path, checkout ., checkout -f, restore without --staged only, switch --discard-changes |
block | uncommitted work has no reflog |
stash clear, reflog expire, gc --prune, prune, filter-branch, filter-repo, update-ref -d, rm on .git |
block | removes the recovery net itself |
branch -D, stash drop, commit --no-verify, checkout name when name is also an existing path |
ask | recoverable, or possibly a branch switch |
commit, rebase, merge, reset --soft, clean -n, push --dry-run, the rest |
pass | the reflog can undo it |
- Whole team, this repository: hook in
.claude/settings.json, script in.claude/hooks/git-guard.py, both committed. - Only you, this repository: hook in
.claude/settings.local.json, same script path. - Every project on this machine: hook in
~/.claude/settings.json, script in~/.claude/hooks/git-guard.py.
2. Write the script
Save this as git-guard.py in the hooks directory chosen above and edit the three constants at the top to match the policy.
#!/usr/bin/env python3
"""Claude Code PreToolUse hook: stop git commands that destroy work or publish it unasked."""
import json, os, re, shlex, sys
PROTECTED = {"main", "master", "production"} # Claude never pushes to these
PLAIN_PUSH = "ask" # every other push: "ask", "allow" or "deny"
FREE_PREFIXES = () # e.g. ("claude/",): pushes to these branches pass silently
VALUE_OPTS = {"-C", "-c", "--git-dir", "--work-tree", "--namespace", "--config-env"}
SHELLS = {"sh", "bash", "zsh", "dash", "ksh", "fish"}
OPERATOR = re.compile(r"^[();<>|&\n]+$")
def current_branch(cwd): # reads HEAD from disk, follows a worktree's gitdir file, spawns nothing
d = os.path.abspath(cwd)
while True:
dot = os.path.join(d, ".git")
if os.path.isfile(dot):
dot = os.path.join(d, open(dot).read().split("gitdir:", 1)[-1].strip())
if os.path.isfile(os.path.join(dot, "HEAD")):
ref = open(os.path.join(dot, "HEAD")).read().strip()
return ref.split("refs/heads/", 1)[-1] if ref.startswith("ref:") else ""
if os.path.dirname(d) == d:
return ""
d = os.path.dirname(d)
def check_git(argv, cwd): # argv = the words after "git"; returns (verdict, reason) or None
i = 0
while i < len(argv) and argv[i].startswith("-"): # global options before the subcommand
if argv[i] == "-C" and i + 1 < len(argv):
cwd = os.path.join(cwd, argv[i + 1])
i += 2 if argv[i] in VALUE_OPTS else 1
if i >= len(argv):
return None
sub, args = argv[i], argv[i + 1:]
longs = {a.split("=")[0] for a in args if a.startswith("--")}
shorts = "".join(a[1:] for a in args if re.match(r"^-[A-Za-z]+$", a))
words = [a for a in args if not a.startswith("-")]
dry = "n" in shorts or "--dry-run" in longs
if sub == "push" and not dry:
if longs & {"--force", "--mirror"} or "f" in shorts or any(a.startswith("+") for a in args):
return "deny", "force push overwrites commits on the remote"
here = current_branch(cwd)
targets = [w.split(":")[-1].replace("refs/heads/", "") for w in words[1:]] or [here]
targets = [here if t in ("HEAD", "@") else t for t in targets]
mass = longs & {"--delete", "--
Установить git-guardrails-claude-code в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл git-guardrails-claude-code?
Installs a Claude Code PreToolUse hook that stops destructive git commands before the shell runs them: force pushes, pushes to protected branches, reset --hard, clean -f, checkouts and restores that discard edits, stash clear and history rewrites, while risky but legitimate commands become a confirmation prompt. Use when someone says "stop Claude from pushing", "block git push --force", "protect main from Claude Code", "add git safety hooks", "Claude wiped my changes with reset --hard", or wants guardrails before running Claude Code in auto mode or with permissions bypassed.
Как установить скилл git-guardrails-claude-code?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл git-guardrails-claude-code запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic