Preventing git commit --amend with Claude Code Hooks
claude-code git hooks
Here’s how I prevent git commit --amend
using Claude Code’s hook system.
During the commit operation, when the pre-commit hook fails, Claude Code has a tendency to use git commit --amend
instead of correcting and retrying git commit
.
This makes for a messy history, where commits contain unrelated changes.
Hook Configuration
Add this to your Claude Code settings:
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "<repo-path>/.claude/pre_command_hook.py"
}
]
}
]
}
Hook Script
Create .claude/pre_command_hook.py
:
#!/usr/bin/env python3
"""
Pre-command hook for Claude Code to prevent git commit --amend
"""
import json
import sys
def main():
try:
# Read input from stdin
input_data = json.load(sys.stdin)
# Get the command from the tool input
command = input_data.get("tool_input", {}).get("command", "")
# Check if it's a git commit command with --amend
if "git commit" in command and "--amend" in command:
print("ERROR: git commit --amend is not allowed in this project. Please use regular commits instead.", file=sys.stderr)
sys.exit(2) # Block the command
# Allow all other commands
sys.exit(0)
except Exception as e:
# If there's any error parsing, allow the command to proceed
print(f"Hook error: {e}", file=sys.stderr)
sys.exit(0)
if __name__ == "__main__":
main()
The hook intercepts all Bash commands, checks for git commit --amend
, and blocks execution with exit code 2.
Note: Claude Code can generate both the hook configuration and script for you automatically. 🧠