npm package: @ginanjarfm/git-commit
Description: Automatically generates conventional commit messages using LLM via OpenRouter
Author: git-commit contributors
Latest version: 1.1.0

# @ginanjarfm/git-commit

[![npm version](https://badge.fury.io/js/@ginanjarfm%2Fgit-commit.svg)](https://badge.fury.io/js/@ginanjarfm%2Fgit-commit)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Node.js Version](https://img.shields.io/badge/node-%3E%3D14.0.0-brightgreen)](https://nodejs.org/)

Automatically generates conventional commit messages using Large Language Models (LLMs) via OpenRouter API. This CLI tool analyzes your staged git changes and creates descriptive, consistent commit messages that follow the conventional commits specification.

## Description

`git-commit` is an intelligent CLI tool that revolutionizes your git workflow by automatically generating high-quality commit messages. It analyzes your code changes using git diff or git status and leverages powerful LLMs through OpenRouter to create conventional commit messages that are descriptive, consistent, and meaningful.

### Key Features

- 🤖 **AI-Powered Generation**: Uses state-of-the-art LLMs to understand your code changes
- 📝 **Conventional Commits**: Automatically follows the conventional commits specification
- ⚙️ **Multiple LLM Models**: Support for OpenAI GPT, Anthropic Claude, and other models via OpenRouter
- 🎨 **Beautiful CLI Interface**: Colorful, intuitive command-line experience
- 🔧 **Interactive Configuration**: Easy setup and configuration management
- 📊 **Smart Analysis**: Analyzes both staged and unstaged changes
- 🔍 **Preview Mode**: Dry-run option to preview messages without committing
- ⚡ **Fast & Efficient**: Quick analysis and generation process

## Installation

### Global Installation (Recommended)

Install globally to use `git-commit` from anywhere:

```bash
npm install -g @ginanjarfm/git-commit
```

### Local Installation

Install locally in your project:

```bash
npm install @ginanjarfm/git-commit
```

Then use with npx:

```bash
npx @ginanjarfm/git-commit
```

## Quick Start

1. **Install the tool globally:**
   ```bash
   npm install -g @ginanjarfm/git-commit
   ```

2. **Configure your OpenRouter API key:**
   ```bash
   git-commit config
   ```

3. **Stage your changes and generate a commit:**
   ```bash
   git add .
   git-commit
   ```

That's it! The tool will analyze your changes and generate a conventional commit message.

## Usage

### Basic Usage

Generate a commit message from staged changes:

```bash
git-commit
```

This is equivalent to:

```bash
git-commit --diff --staged
```

### Command Options

| Option | Description | Default |
|--------|-------------|---------|
| `--diff` | Use git diff for staged changes | `true` |
| `--status` | Use git status instead of git diff | `false` |
| `--staged` | Use staged changes | `true` |
| `--unstaged` | Use unstaged changes | `false` |
| `--type <type>` | Manual override for commit type | - |
| `--scope <scope>` | Manual override for scope | - |
| `--dry-run` | Preview message without committing | `false` |

### Usage Examples

**Basic commit from staged changes:**
```bash
git add .
git-commit
```

**Use git status instead of git diff:**
```bash
git-commit --status
```

**Analyze unstaged changes:**
```bash
git-commit --unstaged
```

**Manual type and scope override:**
```bash
git-commit --type=fix --scope=auth
```

**Preview mode (dry run):**
```bash
git-commit --dry-run
```

**Configure settings:**
```bash
git-commit config
```

### Command Help

Get help and see all available options:

```bash
git-commit --help
```

## Configuration

### Initial Setup

Run the interactive configuration setup:

```bash
git-commit config
```

This will prompt you to:
- Enter your OpenRouter API key
- Select your preferred LLM model
- Configure the base URL (usually default is fine)

### Configuration File

The configuration is stored in `~/.git-commit/config.json`. You can manually edit this file if needed.

#### Example Configuration

```json
{
  "api_key": "your-openrouter-api-key",
  "base_url": "https://openrouter.ai/api/v1",
  "model": "openai/gpt-4o"
}
```

### Supported Models

The tool supports various LLM models through OpenRouter:

| Model | Provider | Description |
|-------|----------|-------------|
| `openai/gpt-4o` | OpenAI | Latest GPT-4 model (recommended) |
| `openai/gpt-4o-mini` | OpenAI | Faster, cost-effective GPT-4 |
| `openai/gpt-3.5-turbo` | OpenAI | Fast and reliable |
| `anthropic/claude-3-haiku` | Anthropic | Fast, cost-effective |
| `anthropic/claude-3-sonnet` | Anthropic | Balanced performance |
| `anthropic/claude-3-opus` | Anthropic | Highest quality |

## Examples

### Complete Workflow Example

```bash
# Make some changes to your code
echo "console.log('Hello, world!');" > hello.js

# Stage the changes
git add hello.js

# Generate and commit with AI
git-commit

# Output:
# 🔍 Analyzing staged changes...
# 🤖 Generating commit message...
# 
# ✓ Generated commit message:
# ┌─────────────────────────────────────────────────────────────────────────────┐
# │ feat: add hello world console log                                           │
# └─────────────────────────────────────────────────────────────────────────────┘
# 
# Based on: staged diff
# 
# ? Do you want to commit with this message? (Y/n)
```

### Using Manual Overrides

```bash
# Force a specific type and scope
git-commit --type=fix --scope=auth --dry-run

# Output will show a commit message like:
# fix(auth): resolve token validation issue
```

### Analyzing Different Change Types

```bash
# Analyze staged changes (default)
git-commit

# Analyze unstaged changes
git-commit --unstaged

# Use git status for analysis
git-commit --status
```

## Conventional Commits

This tool generates commit messages following the [Conventional Commits](https://www.conventionalcommits.org/) specification:

### Format

```
<type>[optional scope]: <description>

[optional body]

[optional footer(s)]
```

### Common Types

- **feat**: A new feature
- **fix**: A bug fix
- **docs**: Documentation only changes
- **style**: Changes that do not affect the meaning of the code
- **refactor**: A code change that neither fixes a bug nor adds a feature
- **perf**: A code change that improves performance
- **test**: Adding missing tests or correcting existing tests
- **chore**: Changes to the build process or auxiliary tools

### Examples

```
feat(auth): add JWT token validation
fix(api): resolve null pointer exception in user service
docs(readme): update installation instructions
style(components): fix indentation in header component
refactor(utils): simplify date formatting function
test(auth): add unit tests for login functionality
chore(deps): update dependencies to latest versions
```

## API Integration (OpenRouter)

### Getting an OpenRouter API Key

1. Visit [OpenRouter](https://openrouter.ai/)
2. Sign up for a free account
3. Navigate to the "Keys" section in your dashboard
4. Generate a new API key
5. Copy the key and use it in the configuration

### Why OpenRouter?

OpenRouter provides:
- Access to multiple LLM providers through a single API
- Competitive pricing and pay-per-use model
- No need for multiple API keys
- Consistent interface across different models
- Transparent pricing and usage tracking

### Cost Considerations

- Most models cost fractions of a cent per commit message
- Typical usage: $0.001 - $0.01 per commit message
- You only pay for what you use
- No monthly subscriptions required

## Development

### Prerequisites

- Node.js 14.0.0 or higher
- npm or yarn
- Git repository for testing

### Setup Development Environment

1. **Clone the repository:**
   ```bash
   git clone https://github.com/ginanjarfm/git-commit.git
   cd git-commit
   ```

2. **Install dependencies:**
   ```bash
   npm install
   ```

3. **Link for local development:**
   ```bash
   npm link
   ```

4. **Run tests:**
   ```bash
   npm test
   ```

### Project Structure

```
git-commit/
├── bin/
│   └── git-commit.js          # CLI entry point
├── lib/
│   ├── config.js              # Configuration management
│   ├── generate.js            # LLM integration and message generation
│   └── git.js                 # Git operations (diff, status)
├── test/
│   ├── cli.test.js            # CLI integration tests
│   ├── fixtures/              # Test fixtures
│   └── lib/                   # Unit tests for library modules
├── package.json               # Package configuration
├── README.md                  # This file
└── LICENSE                    # MIT License
```

### Core Modules

- **`bin/git-commit.js`**: Main CLI interface using Commander.js
- **`lib/config.js`**: Configuration loading, saving, and validation
- **`lib/git.js`**: Git operations (diff, status, repository detection)
- **`lib/generate.js`**: LLM API integration and message generation

## Testing

### Running Tests

```bash
# Run all tests
npm test

# Run tests in watch mode
npm run test:watch

# Run tests with coverage
npm run test:coverage
```

### Test Structure

The project includes comprehensive tests:

- **Unit Tests**: Test individual modules in isolation
- **Integration Tests**: Test CLI functionality end-to-end
- **Fixtures**: Sample git diff and status outputs for testing

### Test Coverage

The test suite covers:
- Configuration management
- Git operations
- Message generation
- CLI interface
- Error handling
- Edge cases

## Troubleshooting

### Common Issues

**"Not in a git repository" error:**
```bash
# Make sure you're in a git repository
git init
```

**"No staged changes found" error:**
```bash
# Stage some changes first
git add .
```

**"API key not configured" error:**
```bash
# Run the configuration setup
git-commit config
```

**"Invalid API key" error:**
- Verify your OpenRouter API key is correct
- Check that you have credits in your OpenRouter account
- Ensure the API key has the necessary permissions

### Debug Mode

For debugging, you can check the configuration:

```bash
# View current configuration (API key will be masked)
git-commit config
```

### Network Issues

If you encounter network issues:
- Check your internet connection
- Verify OpenRouter service status
- Try a different model if one is not responding

### Getting Help

If you encounter issues:

1. Check this troubleshooting section
2. Review the [OpenRouter documentation](https://openrouter.ai/docs)
3. File an issue on the GitHub repository
4. Include error messages and steps to reproduce

## Contributing

Contributions are welcome! Here's how you can help:

### Ways to Contribute

- 🐛 **Report Bugs**: File detailed bug reports
- 💡 **Suggest Features**: Propose new functionality
- 📝 **Improve Documentation**: Help make docs clearer
- 🔧 **Submit Code**: Fix bugs or add features
- 🧪 **Add Tests**: Improve test coverage

### Development Process

1. **Fork the repository**
2. **Create a feature branch:**
   ```bash
   git checkout -b feature/amazing-feature
   ```
3. **Make your changes**
4. **Add tests for new functionality**
5. **Ensure all tests pass:**
   ```bash
   npm test
   ```
6. **Commit using conventional commits:**
   ```bash
   git-commit  # Use the tool itself!
   ```
7. **Push to your fork and submit a pull request**

### Code Style

- Follow existing code style
- Use meaningful variable and function names
- Add JSDoc comments for functions
- Ensure tests pass and maintain coverage

### Pull Request Guidelines

- Provide a clear description of changes
- Include tests for new functionality
- Update documentation if needed
- Follow conventional commit format
- Ensure CI passes

## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

### MIT License Summary

- ✅ Commercial use
- ✅ Modification
- ✅ Distribution
- ✅ Private use
- ❌ Liability
- ❌ Warranty

## Support

### Getting Help

- 📖 **Documentation**: Check this README first
- 🐛 **Bug Reports**: [File an issue](https://github.com/ginanjarfm/git-commit/issues)
- 💬 **Questions**: Use GitHub Discussions
- 📧 **Security Issues**: Email security@example.com

### Roadmap

Future enhancements planned:

- [ ] **Custom Templates**: Support for custom commit message templates
- [ ] **Git Hooks Integration**: Automatic integration with git hooks
- [ ] **Batch Processing**: Process multiple commits at once
- [ ] **Additional Providers**: Support for more LLM providers
- [ ] **History Analysis**: Learn from your commit history
- [ ] **Team Configuration**: Shared team settings
- [ ] **VS Code Extension**: IDE integration
- [ ] **Commit Message Validation**: Validate existing commit messages

---

**Made with ❤️ for developers who care about clean git history**

*Star ⭐ this repository if you find it useful!*