Skip to content

LLM based git-hook script that leverages the model to generate conventional commit style message based on context gather around the diff. In Case it doesn't work for you, create an Issue. Works on my machine LOL

Notifications You must be signed in to change notification settings

DSaatz/LLM-git-hooks

Repository files navigation

AI-Powered Git Commit Message Generator

This script generates intelligent commit messages using AI via OpenRouter based on your staged changes and repository context.

Setup

  1. Install the virtual environment and dependencies:

    python setup.py
  2. Configure your OpenRouter API key: Create a .env file in this directory with:

    OPENROUTER_API_KEY=your_openrouter_api_key_here
    

Getting an OpenRouter API Key

OpenRouter provides access to various AI models through a unified API. Here's how to get started:

  1. Sign up for OpenRouter:

  2. Generate your API key:

    • In your account dashboard, go to the "Keys" section
    • Click "Create Key" and give it a name (e.g., "Commit Message Generator")
    • Copy the generated API key
  3. Add the key to your .env file:

    OPENROUTER_API_KEY=sk-or-v1-your-actual-key-here
    

Why OpenRouter?

  • Access to multiple AI models (GPT-4, Claude, Llama, etc.)
  • Often cheaper than direct provider APIs
  • No need for separate API keys for different providers
  • Easy model switching by changing the model parameter
  • Also most importantly Free models without big limits available 🤑

Usage as Git Hook

To use this as a prepare-commit-msg git hook:

Option 1: Automatic installation (Recommended)

# Navigate to any git repository where you want to use this hook
cd /path/to/your/git/repository

# Run the installer from your scripts folder
python /path/to/commit-msg-gen/install.py

Option 2: Manual installation for specific repository

# Copy the entire directory to your project's git hooks
cp -r /path/to/commit-msg-gen /path/to/your/project/.git/hooks/commit-msg-gen

# Create a symlink to the hook script
cd /path/to/your/project/.git/hooks
ln -s commit-msg-gen/prepare-commit-msg prepare-commit-msg

# On Windows, you might prefer the batch file:
# ln -s commit-msg-gen/prepare-commit-msg.bat prepare-commit-msg

Option 3: Global git hook (for all repositories)

Windows (PowerShell):

# Set up a global git hooks directory
git config --global core.hooksPath "C:\Users\$env:USERNAME\.githooks"

# Create the global hooks directory if it doesn't exist
New-Item -ItemType Directory -Force -Path "C:\Users\$env:USERNAME\.githooks"

# Copy the commit-msg-gen directory (adjust source path as needed)
Copy-Item -Recurse "C:\Users\$env:USERNAME\Documents\scripts\commit-msg-gen" "C:\Users\$env:USERNAME\.githooks\commit-msg-gen"

# Create the hook file as a Python script (works better on Windows)
@"
#!/usr/bin/env python
import subprocess
import sys
import os

# Path to the virtual environment Python
venv_python = os.path.join(os.environ['USERPROFILE'], '.githooks', 'commit-msg-gen', 'venv', 'Scripts', 'python.exe')
main_script = os.path.join(os.environ['USERPROFILE'], '.githooks', 'commit-msg-gen', 'main.py')

# Run the main script with all arguments
try:
    result = subprocess.run([venv_python, main_script] + sys.argv[1:], check=False)
    sys.exit(result.returncode)
except Exception as e:
    print(f'Error running commit message generator: {e}', file=sys.stderr)
    sys.exit(1)
"@ | Out-File -FilePath "C:\Users\$env:USERNAME\.githooks\prepare-commit-msg" -Encoding UTF8

Linux/macOS:

# Set up a global git hooks directory
git config --global core.hooksPath "$HOME/.githooks"

# Create the global hooks directory if it doesn't exist
mkdir -p "$HOME/.githooks"

# Copy the commit-msg-gen directory
cp -r /path/to/commit-msg-gen "$HOME/.githooks/commit-msg-gen"

# Create the hook file that calls our script
cat > "$HOME/.githooks/prepare-commit-msg" << 'EOF'
#!/bin/bash
"$HOME/.githooks/commit-msg-gen/venv/bin/python" "$HOME/.githooks/commit-msg-gen/main.py" "$@"
EOF

# Make it executable
chmod +x "$HOME/.githooks/prepare-commit-msg"

Option 4: Direct execution

You can also run the script directly:

python main.py --generate-only    # Just generate and print the message
python main.py --verbose          # Show context information

Using the Hook

Once installed, the hook will automatically run when you commit. Here's how it works:

Normal Git Workflow:

# 1. Stage your changes as usual
git add .

# 2. Start a commit (this triggers the hook)
git commit
# The hook will generate an AI message and open your editor with it pre-filled
# You can edit, accept, or completely replace the suggested message

# 3. Save and close the editor to complete the commit

Hook Behavior:

  • With -m flag: git commit -m "your message" - Hook is bypassed, your message is used directly
  • Without -m flag: git commit - Hook generates AI message, opens editor for you to review/edit
  • Interactive commits: git commit -v or git commit --verbose - Hook still works, adds AI message to the template

Examples:

# This uses the AI-generated message (you can edit it in the editor)
git commit

# This bypasses the hook entirely - uses your message directly  
git commit -m "fix: resolve authentication bug"

# This shows the diff in the editor along with the AI message
git commit -v

# For testing the hook without committing
git commit --dry-run

What You'll See:

When you run git commit, your default editor will open with something like:

feat: add user authentication system

Implement JWT-based authentication with login/logout endpoints
and middleware for protected routes

# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
# On branch main
# Changes to be committed:
#	modified:   src/auth.py
#	new file:   src/middleware.py

You can then:

  • Accept as-is: Just save and close
  • Edit the message: Modify any part of the generated message
  • Replace entirely: Delete everything and write your own message
  • Abort: Leave the message empty to cancel the commit

How it works

  1. The hook wrapper (prepare-commit-msg or prepare-commit-msg.bat) ensures the virtual environment is activated
  2. It then runs main.py which:
    • Extracts context from your repository (staged changes, recent commits, etc.)
    • Sends this context to OpenRouter API
    • Generates an appropriate commit message
    • Outputs the message for git to use

Files

  • setup.py - Sets up virtual environment and installs dependencies
  • install.py - Automatic installer for git repositories
  • prepare-commit-msg - Unix/Linux hook wrapper
  • prepare-commit-msg.bat - Windows hook wrapper
  • main.py - Main script entry point
  • requirements.txt - Python dependencies
  • .gitignore - Git ignore rules for Python projects
  • prompt.txt - System prompt for the AI model (Conventional Commits style)
  • message_generator.py - OpenRouter API integration
  • context_extracor.py - Repository context extraction (note: filename has typo)
  • git_repository.py - Git operations helper

Troubleshooting

  • "Virtual environment not found": Run python setup.py first
  • "Prompt file 'prompt.txt' not found": Make sure prompt.txt exists in the same directory as the script
  • "Exec format error" on Windows: Make sure the hook file is created as a Python script (not batch file)
  • OpenRouter API errors: Check your .env file and API key
  • Permission denied: Make sure hook files are executable (chmod +x prepare-commit-msg)

Overview if you're to lazy to read

About

LLM based git-hook script that leverages the model to generate conventional commit style message based on context gather around the diff. In Case it doesn't work for you, create an Issue. Works on my machine LOL

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published