Tutorials & Guides
How to Build a Local Git Hook with Claude 3.5 Sonnet to Auto-Generate Semantically Correct Commit Messages
Stop writing lazy git commit messages. Learn how to build a local Git hook that uses Claude 3.5 Sonnet to instantly generate clean, Conventional Commits from your staged diffs.
Updated 11/4/2026
Writing Git commit messages is the tax we pay for collaborating with other humans. Yet, after four hours of chasing a memory leak, most of us lack the mental bandwidth to write a thoughtful summary. We end up committing with lazy classics like fix: typo, updated code, or the dreaded stuff.
We can do better. By harnessing Claude 3.5 Sonnet, we can build a local Git hook that intercepts your commit process, analyses your staged diff, and pre-populates your commit template using the strict Conventional Commits specification. No more mental load, no more messy git logs, and absolutely no manual drafting.
Here is how to build a lightweight, local, and incredibly smart Git hook using Claude and Python.
The Architecture: Why a Hook?
We do not want an annoying, heavy CLI tool that requires we run a custom command like ai-commit. Instead, we want to use native Git architecture.
Git provides a hook called prepare-commit-msg. This hook runs after you type git commit but before your default text editor opens. It is the perfect injection point. Our hook will:
1. Check if a commit message has already been provided (e.g., via git commit -m "message"). If it has, we stand down and let you work.
2. Extract the current staged diff.
3. Send that diff to Claude with a highly constrained prompt.
4. Write Claude’s response back into the Git commit template file, letting you review, edit, or approve it before finalizing the commit.
It ticks every box: it is automated, non-intrusive, and keeps you in complete control of what actually gets committed.
Which AI should I use for this?
Tickd is independent and not affiliated with any AI company.
Step 1: Writing the Python Parser
First, we need a helper script to interact with the Anthropic API. Python is perfect here because of its native libraries and clean scriptability.
Create a directory in your home folder to house your global helper scripts (e.g., ~/.config/git-helpers/) and create a file named semantic_commit.py:
`python
#!/usr/bin/env python3
import os
import sys
import subprocess
import urllib.request
import json
Quick sanity check for the API key API_KEY = os.environ.get("ANTHROPIC_API_KEY") if not API_KEY: print("Error: ANTHROPIC_API_KEY environment variable not set.") sys.exit(1)
def get_staged_diff(): try: # Grab only the staged code changes diff = subprocess.check_output( ["git", "diff", "--cached", "--no-color"], text=True ) return diff.strip() except subprocess.CalledProcessError: print("Error: Could not retrieve git diff.") sys.exit(1)
def generate_commit_message(diff): if not diff: return "" # No staged changes to parse
System prompt to keep Claude strictly on track system_prompt = ( "You are an expert software engineer. Your single task is to generate " "a clean, concise commit message based on the provided git diff. " "You must follow the Conventional Commits 1.0.0 specification structure: " "<type>(<optional scope>): <description>\\n\\n[optional body]. " "Allowed types: feat, fix, docs, style, refactor, perf, test, build, ci, chore. " "Keep the first line under 72 characters. Do not output any markdown formatting, " "do not output any conversational text, explanations, or greeting. " "Output only the raw commit message text." )
url = "https://api.anthropic.com/v1/messages" headers = { "x-api-key": API_KEY, "anthropic-version": "2023-06-01", "content-type": "application/json" } # We use Claude 3.5 Sonnet for precise reasoning over diffs data = { "model": "claude-3-5-sonnet-20241022", "max_tokens": 150, "system": system_prompt, "messages": [ { "role": "user", "content": f"Generate a commit message for this diff:\\n\\n{diff}" } ], "temperature": 0.1 # Low temperature for consistent, logical output }
req = urllib.request.Request( url, data=json.dumps(data).encode("utf-8"), headers=headers, method="POST" )
try: with urllib.request.urlopen(req) as response: res_data = json.loads(response.read().decode("utf-8")) return res_data["content"][0]["text"].strip() except Exception as e: print(f"Warning: Failed to contact Claude API. {e}", file=sys.stderr) return ""
def main(): diff = get_staged_diff() if not diff: sys.exit(0) message = generate_commit_message(diff) if message: print(message)
if __name__ == "__main__":
main()
`
Ensure this script is executable:
`bash
chmod +x ~/.config/git-helpers/semantic_commit.py
`
Step 2: Designing the Prompt
If you want to tweak how Claude behaves, the secret lies in the system prompt. For instance, if you prefer lowercase letters, or if you want to enforce Jira ticket integration, you can build custom parameters into the prompt. To build and refine complex rules for your workflows, check out our interactive prompt generator to easily structure your system rules.
In our script, we set the temperature to 0.1. Diff files are dry, structural, and predictable; setting the temperature high will result in Claude being too creative, resulting in flowery prose or essay-long commit bodies. We want pure, deterministic logic.
Step 3: Wire it into the Git Hook
Now we need to create the actual Git hook. A hook is a simple shell script placed in your repository's .git/hooks directory.
Create a file named .git/hooks/prepare-commit-msg inside the local repository you want to use this on:
`bash
#!/bin/bash
Exit early if we are not on an interactive terminal if [ ! -t 0 ]; then exit 0 fi
COMMIT_MSG_FILE=$1 COMMIT_SOURCE=$2
Only run if the user didn't specify a message manually via -m, -F, or merge if [ -z "$COMMIT_SOURCE" ]; then echo "🤖 Consulting Claude 3.5 Sonnet for a semantic commit message..." # Run our Python helper script AI_MSG=$(python3 ~/.config/git-helpers/semantic_commit.py) if [ -n "$AI_MSG" ]; then # Prepend the generated message, leaving space for developer edits TEMP_FILE=$(mktemp) echo "$AI_MSG" > "$TEMP_FILE" echo -e "\n# --- AI Generated Commit Message Above ---" >> "$TEMP_FILE" cat "$COMMIT_MSG_FILE" >> "$TEMP_FILE" mv "$TEMP_FILE" "$COMMIT_MSG_FILE" echo "✅ Claude populated your commit message template." else echo "⚠️ Could not generate commit message. Proceeding with blank template." fi fi ```
Make the hook executable:
`bash
chmod +x .git/hooks/prepare-commit-msg
`
Step 4: Testing the Workflow
Let's put it to the test. Stage a simple file modification:
`bash
echo "const version = '2.1.0';" > app.js
git add app.js
git commit
`
Instead of opening a blank text editor, your terminal will call the Claude API, analyze your changes, and then launch your default editor with the following already written for you:
`text
fix(app): bump version to 2.1.0
--- AI Generated Commit Message Above --- # Please enter the commit message for your changes. Lines starting # with '#' will be ignored, and an empty message aborts the commit. ```
You can now quickly verify that Claude correctly identified the change, make any minor modifications you like, save, and exit. If your internet connection goes down, or if the API limits are reached, the hook gracefully defaults to your normal, blank commit template. No broken workflows.
Troubleshooting and Global Setup
If you encounter API errors, make sure you have your API key set correctly in your shell profile (~/.zshrc or ~/.bashrc):
`bash
export ANTHROPIC_API_KEY="your-actual-key-here"
`
For more complex debugging on model timeouts or handling larger diff payload limits, check our dedicated Claude Platform Troubleshooting Guide.
If you want to apply this hook globally to all repositories you create or clone on your system, you can set up a global git template directory:
`bash
git config --global init.templateDir '~/.git-templates'
mkdir -p ~/.git-templates/hooks
`
Copy your prepare-commit-msg script into ~/.git-templates/hooks/. Every new repository you initialize or clone from this point forward will automatically use your AI-powered commit assistant.
Keep going
Build something with the prompt generator, decode the jargon in the glossary, or compare the tools on our platform deep-dives.