Skip to content

AI-based automatic commit message generator for git repositories

License

Notifications You must be signed in to change notification settings

nseba/commit-ai

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

36 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Commit-AI

CI/CD Pipeline Go Report Card codecov License: MIT Release

A CLI tool that uses AI to generate meaningful commit messages from git diffs. Supports multiple AI providers including Ollama and OpenAI, with customizable prompt templates and ignore patterns.

Features

  • 🤖 AI-Powered: Generate commit messages using various AI providers
  • 🔧 Multi-Provider Support: Ollama (local), OpenAI, and more
  • 🌐 Multi-Language: Generate commit messages in any language
  • 📝 Custom Templates: Use your own prompt templates
  • 🚫 Ignore Patterns: Support for .caiignore files (like .gitignore)
  • ⚙️ Configurable: Flexible configuration via TOML files and environment variables
  • 🐳 Docker Support: Run in containers
  • 📦 Easy Installation: Multiple installation methods

Quick Start

Installation

Using Go (recommended)

go install github.com/nseba/commit-ai/cmd@latest

Using Homebrew (macOS/Linux)

brew tap nseba/tools
brew install commit-ai

Using Docker

docker pull nseba/commit-ai:latest

Download Binary

Download the latest binary from the releases page.

Basic Usage

  1. Set up Ollama (for local AI):

    # Install Ollama
    curl -fsSL https://ollama.ai/install.sh | sh
    
    # Pull a model
    ollama pull llama2
  2. Generate a commit message:

    # In your git repository with staged changes
    commit-ai
    
    # Or specify a path
    commit-ai /path/to/your/repo
    
    # Use the generated message
    git commit -m "$(commit-ai)"

Interactive Features

Commit-AI now includes interactive features for a better workflow:

Show Last Commit Message

# Display the last commit message
commit-ai --show
# or
commit-ai -s

Interactive Editing

# Generate a message and allow editing before use
commit-ai --edit
# or
commit-ai -e

# This will:
# 1. Generate an AI commit message
# 2. Show you the generated message
# 3. Ask how you want to proceed (keep, edit inline, or edit with external editor)

Auto-commit with Generated Message

# Stage changes and commit in one step
commit-ai --add --commit
# or
commit-ai -a -c

# This will:
# 1. Stage all changes (git add .)
# 2. Generate a commit message
# 3. Ask for confirmation
# 4. Create the commit

Combined Interactive Workflow

# Stage, generate, edit, and commit interactively
commit-ai --add --edit --commit
# or
commit-ai -a -e -c

# This provides the full interactive experience:
# 1. Stages all changes
# 2. Generates AI commit message
# 3. Allows you to edit the message
# 4. Commits with final message after confirmation

Configuration

Commit-AI supports hierarchical configuration with the following priority (highest to lowest):

  1. Environment variables (CAI_*)
  2. Project-local configuration (.commitai files)
  3. Global configuration (~/.config/commit-ai/config.toml)
  4. Default values

Global Configuration

The global configuration is stored in ~/.config/commit-ai/config.toml. If it doesn't exist, it will be created with default values.

Project-Local Configuration

You can override global settings on a per-project basis using .commitai files. These files use the same TOML format as the global configuration but only need to specify the values you want to override.

Key features:

  • Partial overrides: Only specify the settings you want to change
  • Cascading configuration: More specific directories override less specific ones
  • Git-aware: Automatically finds the git repository root and applies configurations hierarchically
  • Secure: Path validation prevents malicious file access and path traversal attacks

Configuration discovery:

  1. If you're in a git repository, commit-ai will look for .commitai files from the git root up to your current directory
  2. If not in a git repository, it looks for .commitai in your current directory
  3. More specific directory configurations override less specific ones

Example structure:

my-project/              # Git repository root
├── .commitai           # Project-wide settings
├── frontend/
│   └── .commitai       # Frontend-specific overrides
└── backend/
    └── .commitai       # Backend-specific overrides

Configuration Options

Option Environment Variable Description Default
CAI_API_URL CAI_API_URL API URL for the AI provider http://localhost:11434
CAI_MODEL CAI_MODEL Model name to use llama2
CAI_PROVIDER CAI_PROVIDER AI provider (ollama, openai) ollama
CAI_API_TOKEN CAI_API_TOKEN API token (required for OpenAI) ""
CAI_LANGUAGE CAI_LANGUAGE Language for commit messages english
CAI_PROMPT_TEMPLATE CAI_PROMPT_TEMPLATE Prompt template file name default.txt
CAI_TIMEOUT_SECONDS CAI_TIMEOUT_SECONDS Timeout for AI requests (seconds) 300

Example Configuration

# ~/.config/commit-ai/config.toml

CAI_API_URL = "http://localhost:11434"
CAI_MODEL = "llama2"
CAI_PROVIDER = "ollama"
CAI_API_TOKEN = ""
CAI_LANGUAGE = "english"
CAI_PROMPT_TEMPLATE = "default.txt"
CAI_TIMEOUT_SECONDS = 300

Project-Local Configuration Examples

Basic project override:

# .commitai (in project root)

# Use OpenAI for this project
CAI_PROVIDER = "openai"
CAI_MODEL = "gpt-4"
CAI_API_TOKEN = "your-project-specific-token"

Multi-language project:

# .commitai (in project root)

# Generate commit messages in Spanish for this project
CAI_LANGUAGE = "spanish"

Development environment override:

# .commitai (in development directory)

# Use local model with longer timeout for development
CAI_API_URL = "http://localhost:11435"
CAI_MODEL = "codellama"
CAI_TIMEOUT_SECONDS = 600

Partial configuration example:

# Global config has all settings
# Project .commitai only overrides specific values
CAI_MODEL = "gpt-3.5-turbo"  # Only override the model
CAI_LANGUAGE = "french"      # Only override the language
# All other settings inherited from global config

Example Files

See the included example files for reference:

  • .commitai.example - Template with all configuration options and documentation
  • .commitai.project-example - Real-world example for Go projects

OpenAI Configuration

# ~/.config/commit-ai/config.toml

CAI_API_URL = "https://api.openai.com"
CAI_MODEL = "gpt-3.5-turbo"
CAI_PROVIDER = "openai"
CAI_API_TOKEN = "your-openai-api-key"
CAI_LANGUAGE = "english"
CAI_PROMPT_TEMPLATE = "default.txt"
CAI_TIMEOUT_SECONDS = 300

Prompt Templates

Commit-AI uses Go templates to customize the AI prompts. Templates are stored in ~/.config/commit-ai/.

Default Template

You are an expert developer reviewing a git diff to generate a concise, meaningful commit message.

Language: Generate the commit message in {{.Language}}.

Git Diff:
{{.Diff}}

Based on the above git diff, generate a single line commit message that:
1. Is concise and descriptive (50 characters or less preferred)
2. Uses conventional commit format if applicable (feat:, fix:, docs:, etc.)
3. Describes WHAT changed, not HOW it was implemented
4. Uses imperative mood (e.g., "Add feature" not "Added feature")

Commit Message:

Custom Template Example

Create ~/.config/commit-ai/detailed.txt:

You are reviewing a git diff to create a detailed commit message.

Language: {{.Language}}

Changes:
{{.Diff}}

Generate a commit message with:
- Summary line (50 chars max)
- Blank line
- Detailed explanation if needed

Format as conventional commit (feat/fix/docs/refactor/etc).

Response:

Then update your config:

CAI_PROMPT_TEMPLATE = "detailed.txt"

Ignore Patterns

Use .caiignore files to exclude certain files from diff analysis. The syntax is identical to .gitignore.

Example .caiignore

# Ignore log files
*.log
logs/

# Ignore generated files
dist/
build/
*.generated.go

# Ignore documentation changes for commit message generation
*.md
docs/

# Ignore test files
*_test.go
test/

Place .caiignore files at any level in your repository. Commit-AI will search up the directory tree and apply all applicable ignore patterns.

Advanced Usage

Command Line Options

Commit-AI supports several command-line flags for different workflows:

Flag Short Description
--show -s Show the last commit message
--edit -e Allow editing of the generated commit message
--commit -c Commit the changes with the generated/edited message
--add -a Stage all changes before generating commit message
--path -p Specify path to git repository
--config Specify config file path

Examples

# Show last commit
commit-ai --show

# Generate message with editing option
commit-ai --edit

# Stage all and commit interactively
commit-ai --add --commit

# Full interactive workflow
commit-ai --add --edit --commit

# Work on specific repository
commit-ai --path /path/to/repo --show

Environment Variables

All configuration options can be overridden with environment variables:

export CAI_PROVIDER=openai
export CAI_MODEL=gpt-4
export CAI_API_TOKEN=your-token

commit-ai

Using with Different Providers

Ollama (Local)

# Start Ollama
ollama serve

# Pull a coding-focused model
ollama pull codellama

# Update config or set environment variable
export CAI_MODEL=codellama

commit-ai

OpenAI

export CAI_PROVIDER=openai
export CAI_MODEL=gpt-3.5-turbo
export CAI_API_TOKEN=sk-your-token-here

commit-ai

Docker Usage

Basic Usage

docker run --rm -it \
  -v $(pwd):/workspace \
  -v ~/.config/commit-ai:/home/appuser/.config/commit-ai \
  nseba/commit-ai:latest

With Environment Variables

docker run --rm -it \
  -v $(pwd):/workspace \
  -e CAI_PROVIDER=openai \
  -e CAI_API_TOKEN=your-token \
  nseba/commit-ai:latest

Note: The Docker Hub description is automatically updated from this README via GitHub Actions whenever changes are pushed to the main branch. See Docker Hub Automation docs for details.

Integration with Git Hooks

Create a pre-commit hook to automatically generate commit messages:

#!/bin/sh
# .git/hooks/prepare-commit-msg

if [ -z "$2" ]; then
    commit-ai > "$1"
fi

Shell Integration

Add to your .bashrc or .zshrc:

# Quick commit with AI-generated message
alias gaic='git add . && git commit -m "$(commit-ai)"'

# Interactive commit with AI suggestion
function gai() {
    local msg=$(commit-ai "$1")
    echo "Suggested commit message: $msg"
    read -p "Use this message? (y/n): " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        git commit -m "$msg"
    else
        git commit
    fi
}

Development

Prerequisites

  • Go 1.21 or later
  • Git
  • Make (optional, for using Makefile)

Building from Source

git clone https://github.com/nseba/commit-ai.git
cd commit-ai

# Install dependencies
go mod download

# Build
go build -o commit-ai ./cmd

# Run tests
go test ./...

Using Makefile

# Set up development environment
make dev-setup

# Run tests
make test

# Build for all platforms
make build-all

# Run linting
make lint

# View all available targets
make help

Project Structure

commit-ai/
├── cmd/                    # CLI entry point
├── internal/              # Private application code
│   ├── cli/              # CLI command handling
│   ├── config/           # Configuration management
│   ├── generator/        # AI message generation
│   └── git/              # Git operations and diff handling
├── pkg/                   # Public packages (if any)
├── configs/              # Example configuration files
├── templates/            # Example prompt templates
├── .github/workflows/    # CI/CD pipelines
├── Dockerfile            # Container definition
├── Makefile             # Build automation
└── README.md            # This file

Contributing

We welcome contributions! Please see our Contributing Guide for details.

Quick Contribution Steps

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/my-feature
  3. Make your changes
  4. Run tests: make test
  5. Run linting: make lint
  6. Commit your changes: git commit -m "feat: add my feature"
  7. Push to your fork: git push origin feature/my-feature
  8. Create a Pull Request

Examples

Basic Workflow

# Make some changes to your code
echo "console.log('Hello, World!');" >> app.js
git add app.js

# Generate commit message
commit-ai
# Output: "feat: add hello world logging to app"

# Commit with the generated message
git commit -m "$(commit-ai)"

Different Languages

# Spanish commit messages
export CAI_LANGUAGE=spanish
commit-ai
# Output: "feat: agregar logging de hello world a la app"

# French commit messages
export CAI_LANGUAGE=french
commit-ai
# Output: "feat: ajouter la journalisation hello world à l'app"

Working with Ignore Patterns

# Create .caiignore
echo "*.log" > .caiignore
echo "dist/" >> .caiignore

# Make changes to ignored and non-ignored files
echo "debug info" > debug.log
echo "new feature" >> src/app.js

git add .

# Only src/app.js changes will be analyzed
commit-ai
# Output: "feat: add new feature to app"

Troubleshooting

Common Issues

"No changes to commit"

  • Ensure you have staged changes: git add .
  • Check if all changes are being ignored by .caiignore patterns

"Failed to connect to AI provider"

  • For Ollama: Ensure Ollama is running (ollama serve)
  • For OpenAI: Check your API token and internet connection
  • Verify the API URL in your configuration

"Timeout errors with large diffs"

  • Increase CAI_TIMEOUT_SECONDS in your config (default: 300 seconds)
  • For very large initial commits, consider: export CAI_TIMEOUT_SECONDS=600
  • Break large commits into smaller, focused commits when possible

"Template not found"

  • Check if the template file exists in ~/.config/commit-ai/
  • Verify the CAI_PROMPT_TEMPLATE setting in your config

"Permission denied"

  • Ensure the binary has execute permissions: chmod +x commit-ai
  • Check file permissions in ~/.config/commit-ai/

Debug Mode

Set DEBUG=1 to enable verbose logging:

DEBUG=1 commit-ai

Getting Help

  • Create an issue for bugs
  • Start a discussion for questions
  • Check existing issues before creating new ones

License

This project is licensed under the MIT License - see the LICENSE file for details.

Acknowledgments

  • Ollama for providing local AI capabilities
  • OpenAI for their API
  • Cobra for the CLI framework
  • go-git for Git operations
  • All contributors and users of this project

Changelog

See CHANGELOG.md for a detailed list of changes and releases.


Made with ❤️ by nseba

About

AI-based automatic commit message generator for git repositories

Topics

Resources

License

Contributing

Security policy

Stars

Watchers

Forks

Packages

No packages published