🤖 AI-powered git commit message generator with repository context awareness
Project description
Smart Commit 🤖
An AI-powered git commit message generator with repository context awareness, built with Python and Typer.
Why Smart Commit?
As developers, we know the importance of good commit messages. They serve as a historical record, help with debugging, facilitate code reviews, and make collaboration seamless. But let's be honest - writing detailed, meaningful commit messages consistently is hard.
The Problem
Time Pressure & Context Switching: When you're juggling multiple projects simultaneously, switching between different codebases, technologies, and contexts, it becomes increasingly difficult to craft thoughtful commit messages. What used to be a natural part of your workflow becomes a bottleneck.
Cognitive Load: After spending hours deep in code, the last thing you want to do is context-switch to writing prose. Your brain is in "code mode," not "documentation mode."
Consistency Across Projects: Each project has its own conventions, tech stack, and commit patterns. Maintaining consistency becomes nearly impossible when you're working on 3-4 different repositories in a single day.
The Vicious Cycle: Poor commit messages lead to poor project history. When you need to understand what changed and why (during debugging, code reviews, or onboarding new team members), cryptic messages like "fix stuff" or "update" provide zero value.
The Solution
Smart Commit understands your repository context - the tech stack, recent commit patterns, file changes, and project structure. It generates meaningful, detailed commit messages that:
- Capture the "Why": Not just what changed, but the reasoning behind the change
- Maintain Consistency: Follows your project's established patterns and conventions
- Save Mental Energy: Let AI handle the prose while you focus on the code
- Preserve History: Create a rich, searchable project timeline that actually helps future you
Example of the difference:
Instead of:
fix auth bug
update dependencies
refactor components
You get:
fix(auth): resolve JWT token expiration handling
- Fix race condition in token refresh mechanism
- Add proper error handling for expired tokens
- Update token validation middleware
- Add unit tests for edge cases
This resolves the issue where users were unexpectedly logged out
during active sessions due to improper token lifecycle management.
Smart Commit turns your commit history into a valuable project resource that tells the story of your codebase evolution.
Features
- 🧠 AI-Powered: Uses OpenAI GPT and Anthropic Claude models to generate meaningful commit messages
- 📁 Repository Context: Analyzes your repo structure, tech stack, and recent commits
- ⚙️ Configurable: Global and local configuration with conventional commit support
- 🖥️ CLI Interface: Rich, interactive command-line interface with Typer
- 🔧 MCP Server: Model Context Protocol server for integration with AI assistants
- 🎯 Smart Filtering: Ignore patterns and custom rules per repository
- 📝 Interactive Editing: Edit generated messages before committing
- 🏗️ Context Files: Include project documentation for enhanced understanding
- 🎨 Custom Templates: Configurable commit message formats and examples
- 🪝 Git Hooks: Automatic commit message generation via git hooks
- 🔒 Security: Sensitive data detection to prevent committing secrets
- 📊 Commit Splitting: Smart analysis suggesting how to split large commits
- 💾 Caching: Cache commit messages to speed up repeated generations
- 🔐 Privacy Mode: Exclude file paths and context files from AI prompts
Installation
Requirements
- Python 3.10 or higher
- Git repository (for generating commit messages)
- API key for your chosen AI provider (100+ models supported thanks to LiteLLM)
Using uv (Recommended)
# Install uv if you haven't already
curl -LsSf https://astral.sh/uv/install.sh | sh
# Install and run as a tool (system-wide install)
uv tool install smart-commit-ai
# Use the tool in any repository
sc generate
Using pip
pip install smart-commit-ai
# Install with Anthropic support
pip install smart-commit-ai[anthropic]
# Install with all optional dependencies
pip install smart-commit-ai[all]
Quick Setup
smart-commit is configured primarily through environment variables, which is secure and flexible.
# Set your AI model and API key
export AI_MODEL="openai/gpt-4o" # Or "claude-3-sonnet-20240229", "gemini/gemini-1.5-pro", etc.
export AI_API_KEY="your-super-secret-api-key"
# You can add these to your .bashrc, .zshrc, or shell profile to make them permanent.
The AI_MODEL can be set to any model supported by litellm. For a full list of available providers and model names, please refer to the LiteLLM Provider Documentation.
You can also run the setup command to save a fallback configuration file:
# This will guide you through saving a config file.
smart-commit setup
Usage
Generate Commit Messages
# Generate commit message for staged changes
smart-commit generate
# Add additional context
smart-commit generate --message "Fixes issue with user authentication"
# Auto-commit without confirmation
smart-commit generate --auto
# Dry run (generate message only)
smart-commit generate --dry-run
# Non-interactive mode
smart-commit generate --no-interactive
Configuration Management
# Initialize configuration (with optional sample repo config)
smart-commit config --init
# Edit configuration
smart-commit config --edit
# Show current configuration
smart-commit config --show
# Local repository configuration
smart-commit config --init --local
Repository Analysis
# Shows detailed information about the current repository
smart-commit context
# Shows detailed information about a specific repository
smart-commit context /path/to/repo
Commit Splitting Analysis
Analyze staged changes and get suggestions for splitting into logical commits:
# Analyze and suggest commit groups
smart-commit analyze
# Alias: sc analyze
# Show detailed file information for each group
smart-commit analyze --detailed
Example output:
Staged Changes Analysis
Files: 12
Lines: +283 -210
💡 Detected 2 logical commit groups:
Group 1: Source Changes (4 files)
└─ Related source code functionality changes
• smart_commit/cli.py
• smart_commit/config.py
• smart_commit/templates.py
• smart_commit/utils.py
Group 2: Tests (8 files)
└─ Separate test changes for easier review and CI validation
• tests/test_cli.py
• tests/test_config.py
... and 6 more files
Suggested workflow:
1. git reset # Unstage all files
1. Stage and commit Source Changes:
git add "smart_commit/cli.py" "smart_commit/config.py" ...
sc generate
2. Stage and commit Tests:
git add "tests/test_cli.py" "tests/test_config.py" ...
sc generate
Git Hooks Integration
Install git hooks for automatic commit message generation:
# Install prepare-commit-msg hook
smart-commit install-hook
# Alias: sc install-hook
# Install with force (overwrites existing hook)
smart-commit install-hook --force
# Uninstall hook
smart-commit uninstall-hook
Once installed, running git commit (without -m) will automatically generate a commit message using smart-commit.
Security Note: The hook automatically detects potential sensitive data (API keys, tokens, etc.) and will warn you before committing.
Cache Management
Smart-commit caches generated messages to improve performance:
# View cache statistics
smart-commit cache stats
# Clear all cached messages
smart-commit cache clear
# Clear expired cache entries only
smart-commit cache clear-expired
Privacy Mode
Exclude file paths and context files from AI prompts:
# Generate with privacy mode
smart-commit generate --privacy
This is useful when working on sensitive codebases or when you want to minimize data sent to AI providers.
Configuration
Smart-commit supports both global and local configurations:
- Global:
~/.config/smart-commit/config.toml - Local:
.smart-commit.tomlin your repository
Enhanced Configuration Options
The configuration now includes enhanced features for better commit message generation:
[ai]
model = "gpt-4o"
api_key = "your-api-key"
max_tokens = 500
temperature = 0.1
[template]
max_subject_length = 50
max_recent_commits = 5 # Number of recent commits to analyze
include_body = true
include_reasoning = true
conventional_commits = true
# Custom example formats for AI guidance
example_formats = [
"""feat: add user authentication system
- Implement JWT-based authentication
- Add login and logout endpoints
- Include password hashing with bcrypt
- Add authentication middleware for protected routes
This enables secure user sessions and protects sensitive endpoints from unauthorized access."""
]
# Enhanced commit type prefixes with descriptions
[template.custom_prefixes]
feat = "for new features"
fix = "for bug fixes"
docs = "for documentation changes"
style = "for formatting changes"
refactor = "for code refactoring"
test = "for test changes"
chore = "for maintenance tasks"
perf = "for performance improvements"
build = "for build system changes"
ci = "for CI/CD changes"
revert = "for reverting changes"
# Repository-specific configuration with enhanced context
[repositories.my-project]
name = "my-project"
description = "My awesome project"
absolute_path = "/absolute/path/to/project" # Explicit path for accessing context files globally
tech_stack = ["python", "react", "docker"]
ignore_patterns = ["*.log", "node_modules/**"]
context_files = ["README.md", "CHANGELOG.md"] # Files included in AI context
# Comprehensive commit conventions
[repositories.my-project.commit_conventions]
breaking = "Use BREAKING CHANGE: in footer for breaking changes that require major version bump"
scope = "Use scope in parentheses after type: feat(auth): add login system"
subject_case = "Use imperative mood in lowercase: 'add feature' not 'adds feature' or 'added feature'"
subject_length = "Keep subject line under 50 characters for better readability"
body_format = "Wrap body at 72 characters, use bullet points for multiple changes"
body_separation = "Separate subject from body with a blank line"
present_tense = "Use present tense: 'change' not 'changed' or 'changes'"
no_period = "Do not end the subject line with a period"
why_not_what = "Explain why the change was made, not just what was changed"
atomic_commits = "Make each commit a single logical change"
test_coverage = "Include test changes when adding new functionality"
docs_update = "Update documentation when changing public APIs or behavior"
Repository Context Features
Smart-commit automatically detects and uses:
- 📊 Technology Stack: Languages, frameworks, and tools
- 🌿 Branch Information: Active branches and current branch
- 📝 Recent Commits: Configurable number of recent commits for pattern analysis
- 📁 File Structure: Repository organization
- 🔍 Project Metadata: README descriptions and project info
- 📚 Context Files: Project documentation included in AI context
- 🎯 Absolute Paths: Precise file location for multi-repo setups
- 🚫 Ignore Patterns: Custom patterns to exclude files from analysis
- 🗂️ Commit Conventions: Project-specific commit message guidelines
MCP Server Integration
Smart-commit includes MCP (Model Context Protocol) server support for integration with AI assistants like Claude Desktop.
Running as MCP Server
# Run the MCP server directly
python -m smart_commit.mcp
# Or use it in your MCP client configuration
MCP Client Configuration
Add to your MCP client configuration (e.g., Claude Desktop):
{
"mcpServers": {
"smart-commit": {
"command": "python",
"args": ["-m", "smart_commit.mcp"]
}
}
}
Available MCP Tools
analyze_repository: Analyze repository structure and contextgenerate_commit_message: Generate AI-powered commit messagesget_staged_changes: Get current staged changesconfigure_smart_commit: Update configuration settingsget_repository_context: Get detailed repository informationquick_setup: Quick configuration setupshow_configuration: Display current configuration
MCP Resources
repository://current: Current repository informationconfig://smart-commit: Smart-commit configuration
MCP Prompts
commit_message_template: Template for commit message generationrepository_analysis_prompt: Template for repository analysis
Advanced Features
Security: Sensitive Data Detection
Smart-commit automatically scans your staged changes for potential secrets and sensitive data:
Detected patterns:
- API keys (AWS, GitHub, Stripe, Google, etc.)
- Authentication tokens (JWT, Bearer tokens, OAuth)
- Private keys and certificates
- Database connection strings
- Passwords and secrets
- Sensitive files (.env, credentials.json, private keys, etc.)
When sensitive data is detected:
# Interactive mode - prompts for confirmation
smart-commit generate
# Git hook mode - shows warning in commit message editor
git commit # Opens editor with warning message
# Non-interactive mode - aborts automatically
smart-commit generate --no-interactive --dry-run
Example warning in git hook:
# ⚠️ SENSITIVE DATA DETECTED
#
# smart-commit detected potential sensitive data in your changes:
#
# Potential secrets:
# - AWS Access Key: 1 occurrence(s)
# - Generic API Key: 2 occurrence(s)
#
# Please review your changes and:
# 1. Remove sensitive data and try again, OR
# 2. Run 'sc generate --auto' to review and override if this is test data, OR
# 3. Commit manually with 'git commit -m "your message"'
Best practices:
- Use environment variables for secrets
- Add sensitive files to
.gitignore - Use secret management tools (Vault, AWS Secrets Manager, etc.)
- Override warnings only for test/mock data
Custom Ignore Patterns
Add patterns to ignore specific files or changes:
[repositories.my-project]
ignore_patterns = [
"*.log",
"node_modules/**",
"dist/**",
"*.generated.*"
]
Context Files for Enhanced Understanding
Include specific files for additional AI context:
[repositories.my-project]
absolute_path = "/home/user/projects/my-project"
context_files = [
"README.md",
"CHANGELOG.md",
"docs/contributing.md",
"API_REFERENCE.md"
]
The AI will read these files and use their content to better understand your project structure and generate more relevant commit messages.
Custom Commit Types with Descriptions
Define project-specific commit types with clear descriptions:
[template.custom_prefixes]
feat = "for new features"
fix = "for bug fixes"
hotfix = "for critical production fixes"
security = "for security-related changes"
deps = "for dependency updates"
config = "for configuration changes"
Recent Commits Analysis
Configure how many recent commits to analyze for pattern consistency:
[template]
max_recent_commits = 10 # Analyze last 10 commits for patterns
This helps maintain consistency with your existing commit style and conventions.
Examples
Basic Usage
# Stage your changes
git add .
# Generate commit message
smart-commit generate
Example output:
Generated commit message:
feat: add user authentication system
- Implement JWT-based authentication
- Add login and logout endpoints
- Create user session management
- Add password hashing with bcrypt
This change introduces a complete authentication system to secure
user access and manage sessions effectively.
With Enhanced Context
# Generate with additional context
smart-commit generate -m "Resolves GitHub issue #123"
# Auto-commit
smart-commit generate --auto
# Verbose output
smart-commit generate --verbose
Repository Setup with Context Files
# Initialize local config for your project
smart-commit config --init --local
# Will prompt: "Include sample repository configuration? [y/N]"
# This will create configuration including context files
# Edit .smart-commit.toml to specify your context files:
[repositories.my-project]
name = "my-project"
description = "My awesome project description"
absolute_path = "/full/path/to/project"
context_files = ["README.md", "docs/ARCHITECTURE.md"]
Multi-Repository Workflow
For developers working on multiple repositories:
# Global config at ~/.config/smart-commit/config.toml
[repositories.frontend-app]
name = "frontend-app"
description = "React frontend application"
absolute_path = "/home/dev/projects/frontend-app"
tech_stack = ["react", "typescript", "tailwind"]
context_files = ["README.md", "package.json"]
[repositories.backend-api]
name = "backend-api"
description = "Python FastAPI backend"
absolute_path = "/home/dev/projects/backend-api"
tech_stack = ["python", "fastapi", "postgresql"]
context_files = ["README.md", "requirements.txt", "docs/API.md"]
[repositories.mobile-app]
name = "mobile-app"
description = "React Native mobile application"
absolute_path = "/home/dev/projects/mobile-app"
tech_stack = ["react-native", "typescript", "expo"]
context_files = ["README.md", "app.json", "docs/SETUP.md"]
This allows Smart Commit to automatically understand the context of whichever repository you're working in and generate appropriate commit messages.
Environment Variables
EDITOR: Preferred editor for interactive message editing (default: nano)
Troubleshooting
Common Issues
"No staged changes found"
- Make sure you've staged your changes with
git add - Check if you're in a git repository
"API key not configured"
- Run
smart-commit setupto configure your API key
"AI provider error"
- Verify your API key is valid and has sufficient credits
- Check your internet connection
- Try switching to a different model
"Configuration not found"
- Run
smart-commit config --initto create initial configuration - Check if the config file exists at
~/.config/smart-commit/config.toml
"Context file not found"
- Verify the
absolute_pathin your repository configuration is correct - Check that context files exist at the specified locations
- Use relative paths from the repository root if
absolute_pathis not set
Debug Mode
# Run with verbose output for debugging
smart-commit generate --verbose
# Show configuration details
smart-commit config --show
# Analyze repository context
smart-commit context
Development
Setting up Development Environment
# Clone the repository
git clone https://github.com/subhayu99/smart-commit.git
cd smart-commit
# Install uv if you haven't already
curl -LsSf https://astral.sh/uv/install.sh | sh
# Install development dependencies
uv pip install -e ".[dev]"
# Install with all optional dependencies
uv pip install -e ".[all]"
Running Tests
# Run tests
pytest
# Run tests with coverage
pytest --cov=smart_commit
Code Quality
# Format code
black smart_commit/
isort smart_commit/
# Type checking
mypy smart_commit/
# Run pre-commit hooks
pre-commit run --all-files
Building and Publishing
# Build the package
uv build
# Publish to PyPI (maintainers only)
uv publish
Contributing
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Make your changes
- Add tests if applicable
- Run the test suite (
pytest) - Commit your changes with a descriptive message
- Push to your branch (
git push origin feature/amazing-feature) - Create a Pull Request
License
MIT License - see LICENSE file for details.
Roadmap
Completed ✅
- Git hooks integration
- Support for 100+ AI models via LiteLLM (OpenAI, Anthropic, Google, etc.)
- Commit message caching for performance
- Sensitive data detection
- Privacy mode
- Commit splitting analysis
- Command aliases (e.g.,
scforsmart-commit)
Planned 🚧
- Plugin system for custom commit message formats
- Integration with popular Git GUIs
- Pre-commit hook integration
- Team/organization shared configurations
- Webhook support for CI/CD integration
- VS Code extension
- Commit message quality scoring
- Integration with issue tracking systems (GitHub, Jira, etc.)
- Commit message validation and linting
- AI-powered code review suggestions
Support
Made with ❤️ by Subhayu Kumar Bala
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file smart_commit_ai-0.2.4.tar.gz.
File metadata
- Download URL: smart_commit_ai-0.2.4.tar.gz
- Upload date:
- Size: 39.0 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.10.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
a72c3b03d74005bebe3b6c857e1bc61db38f2d6d257fdbe290a4a7c84165a35f
|
|
| MD5 |
eef7f512dfc10fa337335ced4cf44b70
|
|
| BLAKE2b-256 |
1cafd2e2252ecdd27c77e173f4f62fecb1d73ea4a432ea326c8fe9353a68f4f9
|
File details
Details for the file smart_commit_ai-0.2.4-py3-none-any.whl.
File metadata
- Download URL: smart_commit_ai-0.2.4-py3-none-any.whl
- Upload date:
- Size: 44.0 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.10.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
6504ad7576dafb87deb983b1f5c589bac3ab8d6bb369f825376753be2c4389e2
|
|
| MD5 |
501ca9b9e11b8ff060b7ea7631405181
|
|
| BLAKE2b-256 |
1dccb952efb9502bc87a12f98027a0056352a28b9550782e1b5703d5d1b05ce9
|