GitHub - xyassini/gitprompt: ๐Ÿค– Automatically stage files and create perfect commits with AI-generated messages using GPT-4.1

14 min read Original article โ†—

๐Ÿค– gitprompt - AI-Powered Git Assistant

License: MIT TypeScript Bun

An intelligent CLI tool that automatically stages and commits files using AI-powered commit message generation.

โš ๏ธ Note: This tool requires an OpenAI API key to function. It will analyze your code changes and generate commit messages using GPT-4.

โš ๏ธ Vibe Coded: The majority of this code was "vibe coded". I use the tool for my own projects, and I checked for any serious bugs and issues, but still: Use at your own risk.

โœจ Features

  • ๐Ÿค– AI-powered commit messages using GPT-4.1 with conventional commit format
  • ๐Ÿ“Š Line-by-line diff analysis showing exactly what changed
  • ๐ŸŽฏ Smart file grouping for logical commits
  • ๐Ÿ” Detailed change tracking (added/removed/modified lines)
  • โœ… Safety checks to prevent conflicts with existing staged files
  • ๐ŸŽจ Beautiful colored CLI with interactive confirmations
  • โšก YOLO mode for automatic commits without confirmation
  • ๐Ÿ“‹ Custom rules support via .gitprompt file or --rules flag

๐Ÿš€ Installation

Prerequisites

  • Node.js (v18+) or Bun (v1.0+)
  • Git configured with user.name and user.email
  • OpenAI API key (Get one here)

Run directly without installing (Recommended)

Make sure you have a global OPENAI_API_KEY environment variable configured, or you supply it directly to the command. You can run gitprompt directly without installing it globally:

# Run with npx (npm)
npx gitprompt

# Or with bunx (bun)
bunx gitprompt

# With OPENAI_API_KEY
OPENAI_API_KEY=your_api_key_here npx gitprompt
# Or with bunx (bun)
OPENAI_API_KEY=your_api_key_here bunx gitprompt

# With options
npx gitprompt --yolo
bunx gitprompt --help

This approach downloads and runs the latest version on-demand, which is perfect for occasional use or trying out the tool.

Install from npm

# Install globally via npm
npm install -g gitprompt

# Or via yarn
yarn global add gitprompt

# Or via pnpm
pnpm add -g gitprompt

# Or via bun
bun install -g gitprompt

After installation, you can use gitprompt command in any git repository:

Install from GitHub (Development)

# Clone the repository
git clone https://github.com/xyassini/gitprompt.git
cd gitprompt

# Install dependencies
bun install

# Make globally available (optional)
bun link

Environment Setup

Create a .env file or set your OpenAI API key:

# Option 1: Environment variable
export OPENAI_API_KEY="your-api-key-here"

# Option 2: .env file (add to .gitignore!)
echo "OPENAI_API_KEY=your-api-key-here" > .env

๐Ÿ“– Usage

Interactive Mode (Default)

# Navigate to your git repository and run
gitprompt

YOLO Mode

# Skip confirmations and commit everything automatically
gitprompt --yolo
# or short form
gitprompt -y

Dry Run Mode

# Preview what would be committed without actually staging or committing files
gitprompt --dry-run
# or short form
gitprompt -d

# Combine with other flags
gitprompt --dry-run --verbose  # Show detailed output without committing
gitprompt --dry-run --yolo     # Preview all commits automatically

Verbose Mode

# Show detailed logging including the AI system prompt and response
gitprompt --verbose
# or short form
gitprompt -v

# Great for debugging or understanding how the AI analyzes your changes
gitprompt --verbose --dry-run  # See the full AI interaction without committing

Custom Rules File

# Use a custom rules file instead of .gitprompt
gitprompt --rules /path/to/your/rules.txt
# or short form
gitprompt -r ./my-commit-rules.txt

# Example: Use team-specific rules
gitprompt --rules ./team-standards.md --verbose

Combining Flags

# All flags can be combined for powerful workflows
gitprompt --dry-run --verbose --yolo     # Preview all AI decisions automatically
gitprompt --rules ./custom.txt --verbose # Use custom rules with detailed output
gitprompt --yolo --verbose              # Auto-commit with AI interaction details

Help

# View all available options and commands
gitprompt --help

๐ŸŽฏ CLI Options Reference

Flag Short Description Default
--yolo -y Skip confirmations and commit everything automatically false
--dry-run -d Show what would be done without actually staging or committing files false
--rules -r Path to custom rules file (instead of .gitprompt) None
--verbose -v Show detailed logging and system prompt false
--max-tokens -t Maximum number of tokens to use for AI processing 10000
--help Show help information
--version Show version number

CLI Output Example

๐Ÿค– gitprompt - AI-Powered Git Assistant

Options:
  -y, --yolo     Skip confirmations and commit everything automatically
                                                      [boolean] [default: false]
  -d, --dry-run  Show what would be done without actually staging or committing
                 files                                [boolean] [default: false]
  -r, --rules    Path to custom rules file (instead of .gitprompt)      [string]
  -v, --verbose  Show detailed logging and system prompt
                                                      [boolean] [default: false]
      --help     Show help                                             [boolean]
      --version  Show version number                                   [boolean]

๐ŸŽ›๏ธ Configuration

.gitprompt File

You can customize the AI's behavior by creating a .gitprompt file in your repository root. This file allows you to:

  • Define custom commit message formats
  • Set project-specific rules and conventions
  • Override default commit type classifications
  • Add context about your project structure

Example .gitprompt File

# Project-specific commit rules for gitprompt

## Commit Convention
Use conventional commits with these scopes:
- core: Core application logic
- api: API endpoints and routes  
- ui: User interface components
- docs: Documentation changes
- test: Test files and testing utilities
- config: Configuration and build files

## Custom Rules
1. For database migration files, always use "feat(db): add migration for X"
2. For API routes in /routes directory, use "feat(api): add/update X endpoint"
3. For React components, use "feat(ui): add/update X component"
4. For utility functions, prefer "refactor(core): add/update X utility"

## Project Context
This is a Node.js/React application with:
- Express.js backend API
- React frontend with TypeScript
- PostgreSQL database with Prisma ORM
- Jest for testing

When analyzing changes, consider this tech stack for better categorization.

## Special Instructions
- Group related frontend and backend changes together when they implement the same feature
- Separate database migrations into their own commits
- Keep test file changes with their corresponding implementation changes

.gitprompt File Rules

  1. Location: Must be in the git repository root (same directory as .git)
  2. Format: Plain text file, any format you prefer (Markdown recommended)
  3. Content: Any instructions, rules, or context you want the AI to consider
  4. Precedence: Takes priority over default AI instructions
  5. Fallback: If no .gitprompt file exists, default behavior is used

Using Custom Rules Files

Instead of .gitprompt, you can specify any custom rules file:

# Use a different rules file
gitprompt --rules ./commit-standards.md

# Use team-wide rules from a shared location
gitprompt --rules ~/shared/team-commit-rules.txt

# Use rules with other flags
gitprompt --rules ./rules.txt --dry-run --verbose

Environment Setup

Create a .env file or set your OpenAI API key:

# Option 1: Environment variable
export OPENAI_API_KEY="your-api-key-here"

# Option 2: .env file (add to .gitignore!)
echo "OPENAI_API_KEY=your-api-key-here" > .env

๐ŸŽฌ Demo

Standard Interactive Mode

๐Ÿค– gitprompt - AI-Powered Git Assistant

๐Ÿค– Analyzing repository status...
๐Ÿค– Calculating diffs...
โœ… Found 3 file(s) with changes
๐Ÿค– Generating intelligent commit groups...
โ„น๏ธ  Found 2 commit group(s)

๐Ÿ“ฆ Commit Group 1
Message: feat(auth): add user authentication and JWT validation
Files:
  โ€ข src/auth.ts
  โ€ข src/middleware/auth.ts
  โ€ข tests/auth.test.ts

? Commit this group? (y/n) y
๐Ÿค– Staging files: src/auth.ts, src/middleware/auth.ts, tests/auth.test.ts
๐Ÿค– Creating commit: feat(auth): add user authentication and JWT validation
โœ… Committed: feat(auth): add user authentication and JWT validation

๐Ÿ“ฆ Commit Group 2
Message: docs: update API documentation for auth endpoints
Files:
  โ€ข README.md
  โ€ข docs/api.md

? Commit this group? (y/n) y
โœ… All done! ๐ŸŽ‰

Dry Run Mode with Verbose Output

๐Ÿค– gitprompt - AI-Powered Git Assistant

๐Ÿงช DRY RUN MODE: No files will be staged or committed
๐Ÿ” VERBOSE MODE: Detailed logging enabled

๐Ÿค– Analyzing repository status...
Found 4 files in status matrix
Git config: John Doe <john@example.com>
Found 3 unstaged changes:
  src/api.ts (head:1, workdir:2, stage:1)
  tests/api.test.ts (head:0, workdir:2, stage:0)
  README.md (head:1, workdir:2, stage:1)

๐Ÿค– Calculating diffs...
Diff summary:
  src/api.ts: modified (12 diff lines)
  tests/api.test.ts: added (24 diff lines)
  README.md: modified (3 diff lines)

๐Ÿค– Generating intelligent commit groups...

================================================================================
๐Ÿ“‹ SYSTEM PROMPT:
================================================================================
You are a git assistant that analyzes code changes and generates intelligent commit messages.
[... full system prompt displayed ...]

๐Ÿ“ค SENDING TO AI MODEL: gpt-4.1-mini

๐Ÿ“œ Using custom rules from: .gitprompt
Rules content:
Use conventional commits with these scopes:
- api: API endpoints and routes
- test: Test files and testing utilities
- docs: Documentation changes

๐Ÿค– Parsing AI recommendations...
๐Ÿ“ฅ AI RESPONSE:
[
  {
    "files": ["src/api.ts", "tests/api.test.ts"],
    "commitMessage": "feat(api): add user profile endpoint with tests"
  },
  {
    "files": ["README.md"],
    "commitMessage": "docs: update API documentation"
  }
]

โ„น๏ธ  Found 2 commit group(s)
โ„น๏ธ  DRY RUN mode - no files will be staged or committed

๐Ÿ“ฆ Commit Group 1
Message: feat(api): add user profile endpoint with tests
Files:
  โ€ข src/api.ts
  โ€ข tests/api.test.ts

โ„น๏ธ  [DRY RUN] Would stage files: src/api.ts, tests/api.test.ts
โ„น๏ธ  [DRY RUN] Would create commit: feat(api): add user profile endpoint with tests
โœ… [DRY RUN] Would commit: feat(api): add user profile endpoint with tests

๐Ÿ“ฆ Commit Group 2
Message: docs: update API documentation
Files:
  โ€ข README.md

โ„น๏ธ  [DRY RUN] Would stage files: README.md
โ„น๏ธ  [DRY RUN] Would create commit: docs: update API documentation
โœ… [DRY RUN] Would commit: docs: update API documentation

โœ… Dry run completed! ๐ŸŽ‰

Custom Rules Example

๐Ÿค– gitprompt - AI-Powered Git Assistant

๐Ÿ“œ Using custom rules from: ./team-standards.md
Rules content:
Always prefix database changes with "db:" scope
Group UI and API changes together for features

๐Ÿค– Analyzing repository status...
[... analysis continues with custom rules applied ...]

CLI Output

The CLI provides beautiful colored output with:

  • ๐Ÿค– Progress indicators for each step
  • โœ… Success messages when operations complete
  • โŒ Error messages with helpful context
  • ๐Ÿ“ฆ Commit group previews showing files and messages
  • โ“ Interactive prompts for confirmation

Example Session

๐Ÿค– gitprompt - AI-Powered Git Assistant

๐Ÿค– Analyzing repository status...
๐Ÿค– Calculating diffs...
โœ… Found 8 file(s) with changes
๐Ÿค– Generating intelligent commit groups...
๐Ÿค– Parsing AI recommendations...
โ„น๏ธ  Found 3 commit group(s)

๐Ÿ“ฆ Commit Group 1
Message: feat(core): add AI-powered git assistant modules
Files:
  โ€ข src/ai.ts
  โ€ข src/diff.ts
  โ€ข src/git.ts

? Commit this group? (y/n) y
๐Ÿค– Staging files: src/ai.ts, src/diff.ts, src/git.ts
๐Ÿค– Creating commit: feat(core): add AI-powered git assistant modules
โœ… Committed: feat(core): add AI-powered git assistant modules

Project Structure

gitprompt/
โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ git.ts      # Git operations (status, staging, committing)
โ”‚   โ”œโ”€โ”€ diff.ts     # Diff calculation and file content analysis
โ”‚   โ”œโ”€โ”€ ai.ts       # AI integration for commit message generation
โ”‚   โ””โ”€โ”€ utils.ts    # Validation and utility functions
โ”œโ”€โ”€ cli.ts          # CLI interface and user interaction
โ”œโ”€โ”€ index.ts        # Original programmatic interface
โ”œโ”€โ”€ types.ts        # Type definitions
โ””โ”€โ”€ package.json

Module Documentation

cli.ts - CLI Interface

The main CLI application featuring:

  • Argument parsing with yargs
  • Colored output with yoctocolors
  • Interactive prompts for commit confirmation
  • YOLO mode for automated commits
  • Error handling with user-friendly messages

src/git.ts

Handles all git-related operations:

  • getStatusMatrix() - Gets current git status
  • getUnstagedChanges() - Filters for unstaged files
  • getGitConfig() - Reads global git configuration
  • stageFiles() - Stages specific files
  • commitChanges() - Creates commits with author info

src/diff.ts

Manages diff calculation and file analysis:

  • calculateLineDiffs() - Line-by-line comparison
  • calculateDiffForFile() - Complete diff analysis for a file
  • getDiffs() - Processes all unstaged files
  • Determines change types: added, removed, modified, untracked

src/ai.ts

AI integration for intelligent commit grouping:

  • generateCommitGroups() - Calls GPT-4 to analyze changes
  • parseCommitGroups() - Parses AI response into structured data
  • Groups related files and generates conventional commit messages

src/utils.ts

Validation and utility functions:

  • validateNoStagedFiles() - Ensures clean staging area
  • validateNoDiffs() - Checks for changes to process

How It Works

  1. ๐Ÿ” Status Check: Reads git status and validates no files are already staged
  2. ๐Ÿ“Š Diff Analysis: Calculates line-by-line diffs for all unstaged files
  3. ๐ŸŽ›๏ธ Configuration Loading: Reads .gitprompt file or custom rules file (if specified)
  4. ๐Ÿค– AI Processing: Sends diffs and custom rules to GPT-4 for intelligent file grouping and commit message generation
  5. ๐Ÿ“‹ Interactive Review: Shows each commit group and asks for confirmation (unless in YOLO mode)
  6. ๐Ÿงช Dry Run Preview: If in dry-run mode, shows what would be committed without making changes
  7. ๐Ÿ“ Staging & Committing: Stages and commits approved groups sequentially (skipped in dry-run mode)

Development Usage

If you're developing locally from the GitHub repository:

# Interactive mode
bun src/index.ts

# With new flags
bun src/index.ts --dry-run --verbose
bun src/index.ts --rules ./custom-rules.txt
bun src/index.ts --yolo --dry-run

# Help
bun src/index.ts --help

Configuration

  • AI Model: Uses GPT-4.1, configurable in src/ai.ts
  • Git Config: Automatically uses your global git user.name and user.email
  • Colors: Fully customizable in the CLI code

Safety Features

  • โœ… Prevents running when files are already staged
  • โœ… Validates git configuration before proceeding
  • โœ… Interactive confirmations by default (unless --yolo)
  • โœ… Sequential processing to avoid git conflicts
  • โœ… Detailed error handling and user feedback

Requirements

  • Node.js/Bun
  • Git configured with user.name and user.email
  • OpenAI API key for GPT-4 access

Dependencies

  • yargs - Command line argument parsing
  • yoctocolors - Terminal colors and styling
  • @ai-sdk/openai - AI integration
  • isomorphic-git - Git operations in JavaScript

This project was created using bun init in bun v1.2.12. Bun is a fast all-in-one JavaScript runtime.

๐Ÿ”ง Troubleshooting

Common Issues

"Git user.name and user.email must be configured"

git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"

"There are already staged files"

# Either commit existing staged files
git commit -m "your message"
# Or unstage them
git reset

"OpenAI API Error"

  • Verify your API key is set correctly
  • Check your OpenAI account has credits
  • Ensure you have access to GPT-4

"Could not find HEAD"

  • Make sure you're in a git repository
  • Ensure you have at least one commit in your repository

New Features Troubleshooting

".gitprompt file not being used"

  • Ensure the file is in the repository root (same level as .git folder)
  • Check file permissions are readable
  • Use --verbose flag to see if rules are being loaded:
    gitprompt --verbose
    # Look for "Using custom rules from: .gitprompt" message

"Custom rules file not found"

# Verify the file path exists
ls -la /path/to/your/rules.txt

# Use absolute path if relative path isn't working
gitprompt --rules /absolute/path/to/rules.txt

# Check current directory
pwd
gitprompt --rules ./rules.txt

"Dry run mode not showing expected output"

  • Ensure you have unstaged changes: git status
  • Combine with verbose for more details: gitprompt --dry-run --verbose
  • Check that files are actually modified: git diff

"Verbose mode too overwhelming"

# Use dry-run with verbose to see AI behavior without commits
gitprompt --dry-run --verbose

# Redirect verbose output to file for later review
gitprompt --verbose 2> gitprompt-debug.log

# Use verbose only when debugging specific issues
gitprompt --verbose --dry-run | grep -A 10 "SYSTEM PROMPT"

"AI not following custom rules"

  • Verify rules file content is clear and specific
  • Use verbose mode to see the exact prompt sent to AI
  • Check that rules file doesn't contain conflicting instructions
  • Test with simple rules first:
    # Example simple .gitprompt file
    Always use "feat" for new files
    Always use "fix" for bug fixes
    Use scope "core" for src/ directory changes
    

"Flag combinations not working as expected"

# Valid combinations
gitprompt --dry-run --verbose          # โœ… Preview with details
gitprompt --yolo --dry-run            # โœ… Auto-preview all commits
gitprompt --rules ./custom.txt --verbose  # โœ… Custom rules with details

# Note: --yolo with interactive prompts is redundant but harmless
gitprompt --yolo --verbose            # โœ… Auto-commit with AI details

๐Ÿค Contributing

Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

Development Setup

# Clone the repo
git clone https://github.com/xyassini/gitprompt.git
cd gitprompt

# Install dependencies
bun install

# Run in development
bun src/index.ts

Guidelines

  • Follow the existing code style
  • Add tests for new features
  • Update documentation as needed
  • Use conventional commit messages

๐Ÿ”’ Security & Privacy

  • Code Analysis: This tool analyzes your code locally and sends diff information to OpenAI's API
  • No Code Storage: Your code is not stored by the tool or OpenAI beyond the API call
  • API Security: Uses OpenAI's secure API endpoints
  • Local Processing: All git operations happen locally on your machine

๐Ÿ“„ License

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

๐Ÿ™ Acknowledgments

๐Ÿ“ž Support


โญ Star this repo if you find it helpful!

๐Ÿงช Testing

The project includes comprehensive tests for all core functionality:

# Run all tests
bun test

# Run tests in watch mode
bun test --watch

Test Coverage

  • ๐Ÿ› ๏ธ Utils: Validation functions, error handling, logging
  • ๐Ÿ“Š Diff: Line-by-line diff calculation, file change detection
  • ๐Ÿ”ง Git: Status matrix parsing, configuration reading, file staging logic
  • ๐Ÿค– AI: Commit group parsing, error handling

Tests use Bun's built-in test runner with mocking for external dependencies.