ai-commit-validator
v2.4.2
Published
A GitHub Copilot-powered commit validator with intelligent local code analysis, enhanced security pattern detection, automatic error file opening, side-by-side code comparison, and production-ready skip validation directives.
Maintainers
Readme
AI Commit Validator 🤖
An AI-powered commit validator that acts as your intelligent code reviewer before commits. Uses OpenAI's GPT models to analyze your staged changes and provide actionable feedback, similar to GitHub Copilot suggestions.
✨ Features
- 🧠 AI Code Review: Leverages OpenAI's GPT models for intelligent code analysis
- 🔍 Pre-commit Validation: Reviews staged changes before they're committed
- 🎨 Interactive CLI: Beautiful colored output with interactive prompts
- 🛡️ Bypass Protection: Requires justification when skipping AI suggestions
- 📂 Auto-Open Errors: Automatically opens files at error locations (NEW in v2.2.0)
- 🚀 Easy Integration: Simple setup as a git hook or standalone tool
- 📊 Detailed Feedback: Provides clear, actionable improvement suggestions
🚀 Installation
Global Installation
npm install -g ai-commit-validatorLocal Installation
npm install ai-commit-validator⚙️ Configuration
1. OpenAI API Key Setup
Create a .env file in your project root:
OPENAI_API_KEY=your_openai_api_key_hereGetting your OpenAI API Key:
- Visit OpenAI Platform
- Sign up or log in to your account
- Navigate to API Keys section
- Create a new secret key
- Copy and paste it into your
.envfile
Environment Variables
| Variable | Required | Description | Default |
|----------|----------|-------------|---------|
| OPENAI_API_KEY | ✅ Yes | Your OpenAI API key | - |
| AI_AUTO_OPEN_ERRORS | ❌ No | Auto-open files at error locations | false |
| AI_DEFAULT_ON_CANCEL | ❌ No | Default action on prompt timeout | cancel |
| AI_PROMPT_TIMEOUT_MS | ❌ No | Timeout for interactive prompts (ms) | 30000 |
| AI_AUTO_SELECT | ❌ No | Auto-respond in non-interactive mode | - |
| AI_FORCE_PROMPT | ❌ No | Force prompts in non-TTY environments | false |
🎯 Usage
Command Line Interface
# Validate staged changes
validate-commitGit Hook Integration
Option 1: Pre-commit Hook (Recommended)
Create .git/hooks/pre-commit:
#!/bin/sh
# Run AI commit validator
npx validate-commitMake it executable:
chmod +x .git/hooks/pre-commitOption 2: Manual Validation
# Stage your changes
git add .
# Run validation
validate-commit
# If validation passes, commit
git commit -m "Your commit message"Programmatic Usage
import { validateCommit } from 'ai-commit-validator';
// Run validation
await validateCommit();🔄 Workflow
Stage Changes: Add files to git staging area
git add .AI Analysis: The validator automatically:
- Analyzes your staged changes
- Sends the diff to OpenAI for review
- Receives intelligent feedback
Interactive Decision: Based on AI feedback, you can:
- ✅ Apply suggestions - Make recommended changes
- ⚠️ Skip with justification - Bypass with required reason
- ❌ Cancel commit - Stop the commit process
Commit: If validation passes or is bypassed, proceed with commit
📝 Example Output
🔍 Checking your staged changes...
🧠 Sending code diff to AI for review...
🤖 AI Review Feedback:
I found a few areas for improvement:
1. **Security Issue**: The API key is hardcoded in line 15. Consider using environment variables.
2. **Performance**: The loop in `processData()` could be optimized using `map()` instead of `forEach()`.
3. **Error Handling**: Missing try-catch block around the database query on line 23.
What do you want to do?
❯ Apply suggestions and continue
Skip validation with comment
Cancel commit🎨 Features in Detail
AI-Powered Analysis
- Code Quality: Identifies potential bugs, security issues, and performance problems
- Best Practices: Suggests improvements following coding standards
- Documentation: Recommends better comments and documentation
- Refactoring: Suggests cleaner, more maintainable code patterns
Interactive Experience
- Colored Output: Beautiful terminal interface with chalk.js
- Progress Indicators: Clear feedback during AI processing
- Smart Prompts: Contextual questions based on analysis results
Bypass Protection
- Justification Required: Must provide reason when skipping suggestions
- Audit Trail: Logs bypass reasons for team accountability
- Configurable: Can be customized for team requirements
🛠️ Advanced Configuration
Custom AI Model
Modify the model in index.js:
const response = await openai.chat.completions.create({
model: "gpt-4", // Change to your preferred model
messages: [{ role: "user", content: prompt }],
});Custom Prompts
Customize the AI prompt for your team's needs:
const prompt = `
You are a senior code reviewer for our team.
Focus on: security, performance, and maintainability.
Use our team's coding standards: [link to standards]
...
`;🔧 Troubleshooting
Common Issues
Error: No OpenAI API Key
Error: OpenAI API key not foundSolution: Ensure .env file exists with OPENAI_API_KEY=your_key
Error: No staged changes
⚠️ No staged changes foundSolution: Stage files first with git add .
Error: API Rate Limit
Error: Rate limit exceededSolution: Wait a moment and try again, or upgrade your OpenAI plan
Debug Mode
Add debug logging by modifying index.js:
console.log('Debug: Staged diff:', diff);
console.log('Debug: AI Response:', aiFeedback);📊 Performance
- Average Analysis Time: 2-5 seconds
- API Cost: ~$0.001-0.01 per commit (depending on change size)
- Supported File Types: All text-based files (JS, TS, Python, etc.)
🤝 Contributing
- Fork the repository
- Create a feature branch:
git checkout -b feature/amazing-feature - Stage your changes:
git add . - Run the validator:
validate-commit - Commit your changes:
git commit -m "Add amazing feature" - Push to the branch:
git push origin feature/amazing-feature - Open a pull request
📋 Requirements
- Node.js: >= 16.0.0
- Git: Any recent version
- OpenAI API Key: Required for AI analysis
- Internet Connection: Required for API calls
🆕 v2.2.0 - Auto-Open Error Locations
The validator now automatically opens files at error locations with intelligent editor detection!
Features:
- 📂 Opens files directly in VS Code, Sublime Text, or Vim
- 🎯 Navigates to the exact error line
- 💡 Shows fix suggestions in the terminal
- ✅ Fully optional (disabled by default)
Quick Start:
export AI_AUTO_OPEN_ERRORS=true
git commit -m "Your commit message"
# Files with errors open automatically in your editor!Documentation: See FEATURES_2.2.0.md and AUTO_OPEN_ERRORS.md for detailed information.
📜 License
MIT License - see LICENSE file for details.
👨💻 Author
Sanjib Roy
🙏 Acknowledgments
- OpenAI for providing the GPT API
- The open-source community for the excellent libraries used
- GitHub Copilot for inspiration
🔗 Related Projects
- branch-commit-validator - Traditional pattern-based validation
- conventional-changelog - Commit message conventions
📈 Roadmap
- [ ] Support for multiple AI providers (Claude, Gemini)
- [ ] Team-specific rule customization
- [ ] Integration with popular IDEs
- [ ] Batch analysis for multiple commits
- [ ] Custom rule engine
- [ ] Performance metrics and analytics
Made with ❤️ by Sanjib Roy
Transform your commit process with AI-powered code review! 🚀
