diff --git a/.goreleaser.yml b/.goreleaser.yml index 4f47563..93e071f 100644 --- a/.goreleaser.yml +++ b/.goreleaser.yml @@ -37,6 +37,10 @@ archives: format_overrides: - goos: windows format: zip + files: + - .env.example + - README.md + - docs/**/* checksum: name_template: 'checksums.txt' diff --git a/DOCS/CHANGELOG.md b/DOCS/CHANGELOG.md deleted file mode 100644 index d83420d..0000000 --- a/DOCS/CHANGELOG.md +++ /dev/null @@ -1,64 +0,0 @@ -# Changelog - -All notable changes to this project will be documented in this file. - -The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), -and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - -## [Unreleased] - -### Added - -- Cache clear functionality (`commitgen cache --clear`) -- Automatic .env file loading for seamless configuration -- Simplified OpenAI-only integration (removed Ollama complexity) -- Enhanced configuration with smart defaults -- Comprehensive development documentation -- Build automation with Makefile -- MIT License for open-source compliance - -### Changed - -- Streamlined AI provider selection (OpenAI only) -- Improved environment variable handling -- Simplified configuration variable names -- Enhanced .env.example with better documentation - -### Fixed - -- Duplicate commit message suggestions (disabled shell integration conflicts) -- Environment variable loading issues -- Configuration file detection -- API key validation workflow -- Cross-platform CI/CD issues (Windows PowerShell compatibility) - -### Removed - -- Ollama provider support (simplified to OpenAI only) -- Complex provider switching logic -- Redundant configuration options - -## [0.1.0] - Initial Development - -### Added in 0.1.0 - -- Core AI-powered commit message generation -- OpenAI integration with gpt-4o-mini support -- High-performance caching system with git hooks -- Shell integration for zsh autosuggestions -- Git workflow integration (prepare-commit-msg hook) -- Heuristic fallback for offline usage -- Doctor command for system diagnostics -- Professional commit message conventions -- Shell installation/uninstallation commands -- Basic CI/CD pipeline -- Documentation structure - -### Features - -- Sub-100ms commit message retrieval via cache -- Background pre-generation on `git add` -- Ghost text suggestions in terminal -- Smart fallback chain: AI β†’ Cache β†’ Heuristics -- One-command setup experience -- Zero-config defaults with customization options diff --git a/DOCS/CONTRIBUTING.md b/DOCS/CONTRIBUTING.md deleted file mode 100644 index 0f2faec..0000000 --- a/DOCS/CONTRIBUTING.md +++ /dev/null @@ -1,216 +0,0 @@ -# Contributing to commitgen - -Thank you for your interest in contributing to commitgen! This document provides guidelines and information for contributors. - -## πŸš€ Quick Start - -1. **Fork and clone the repository** - - ```bash - git clone https://github.com/joaquinalmora/commitgen.git - cd commitgen - ``` - -2. **Set up development environment** - - ```bash - make dev-setup - make build - ``` - -3. **Run tests** - - ```bash - make test - ``` - -4. **Test your changes** - - ```bash - make dev # Build and test - make doctor # System health check - ``` - -## πŸ› οΈ Development Workflow - -### Building and Testing - -```bash -# Quick development cycle -make dev # Build + test -make test-coverage # Generate coverage report -make clean # Clean artifacts - -# Manual testing -./bin/commitgen suggest --ai --verbose -./bin/commitgen doctor -``` - -### Code Quality - -- **Go formatting**: Code must be `gofmt` formatted -- **Testing**: Add tests for new functionality -- **Documentation**: Update docs for user-facing changes - -### Project Structure - -```text -cmd/commitgen/ # Main application entry point -internal/ -β”œβ”€β”€ cache/ # Caching system -β”œβ”€β”€ config/ # Configuration management -β”œβ”€β”€ diff/ # Git diff processing -β”œβ”€β”€ doctor/ # System diagnostics -β”œβ”€β”€ hook/ # Git hooks -β”œβ”€β”€ prompt/ # Commit message generation -β”œβ”€β”€ provider/ # AI provider integrations -└── shell/ # Shell integration -``` - -## 🎯 Areas for Contribution - -### High Priority - -- **Test coverage expansion** (currently 3/8 packages) -- **Error handling improvements** -- **Performance optimizations** -- **Documentation improvements** - -### Medium Priority - -- **New AI providers** (following the provider interface) -- **Shell integrations** (bash, fish support) -- **Configuration enhancements** - -### Ideas Welcome - -- **VS Code extension** -- **Additional shell features** -- **Commit template customization** - -## πŸ“‹ Pull Request Process - -1. **Create a feature branch** - - ```bash - git checkout -b feature/your-feature-name - ``` - -2. **Make your changes** - - Follow existing code style - - Add tests for new functionality - - Update documentation if needed - -3. **Test thoroughly** - - ```bash - make dev - make test-coverage - ./bin/commitgen doctor - ``` - -4. **Commit with conventional commits** - - ```bash - git commit -m "feat: add new feature description" - # or - git commit -m "fix: resolve issue with ..." - ``` - -5. **Push and create PR** - - ```bash - git push origin feature/your-feature-name - ``` - -## πŸ§ͺ Testing Guidelines - -### Unit Tests - -- Place tests in `*_test.go` files -- Use table-driven tests where appropriate -- Mock external dependencies - -### Integration Tests - -- Test real workflows in `e2e/` directory -- Test shell integration -- Test AI provider integration - -### Manual Testing - -```bash -# Test basic functionality -echo "test" > test.txt && git add test.txt -./bin/commitgen suggest --ai --verbose - -# Test shell integration -make install -# Then test autosuggestions in a new terminal - -# Test system health -./bin/commitgen doctor -``` - -## πŸ“ Commit Message Convention - -We use [Conventional Commits](https://www.conventionalcommits.org/): - -- `feat:` - New features -- `fix:` - Bug fixes -- `docs:` - Documentation changes -- `style:` - Code style changes (formatting, etc.) -- `refactor:` - Code refactoring -- `test:` - Adding or updating tests -- `chore:` - Maintenance tasks - -## πŸ› Bug Reports - -When reporting bugs, please include: - -1. **Environment information** - - ```bash - ./bin/commitgen doctor # Include this output - go version - uname -a - ``` - -2. **Steps to reproduce** -3. **Expected vs actual behavior** -4. **Relevant logs or error messages** - -## πŸ’‘ Feature Requests - -- Check existing issues first -- Describe the use case and motivation -- Consider implementation impact -- Be open to discussion and alternatives - -## πŸ”’ Security - -- Report security vulnerabilities privately -- Use GitHub's security advisory feature -- Don't include sensitive information in public issues - -## πŸ“„ License - -By contributing to commitgen, you agree that your contributions will be licensed under the MIT License. - -## 🀝 Community - -- Be respectful and inclusive -- Help others in discussions -- Share knowledge and best practices -- Follow the project's code of conduct - -## πŸ“ž Getting Help - -- **Documentation**: Check README.md and DOCS/ -- **Issues**: Search existing GitHub issues -- **Discussions**: Use GitHub Discussions for questions -- **Real-time**: Check if there's a community chat - ---- - -Thank you for contributing to commitgen! πŸŽ‰ diff --git a/DOCS/README.md b/DOCS/README.md deleted file mode 100644 index 9987d3f..0000000 --- a/DOCS/README.md +++ /dev/null @@ -1,64 +0,0 @@ -# CommitGen Documentation - -Complete documentation for commitgen - the AI-powered git commit message generator. - -## πŸ“š Documentation Index - -### Getting Started - -- **[Installation & Setup](SETUP.md)** - Complete installation, configuration, and shell integration guide - -### Development - -- **[Contributing Guidelines](CONTRIBUTING.md)** - How to contribute to the project -- **[Technical Reference](TECHNICAL.md)** - Architecture, components, and development guide -- **[Deployment Roadmap](TODO_DEPLOYMENT.md)** - Development progress and deployment checklist -- **[Changelog](CHANGELOG.md)** - Version history and release notes - -## πŸš€ Quick Start - -```bash -# Install via Homebrew (recommended) -brew tap joaquinalmora/tap -brew install commitgen - -# Or via Go -go install github.com/joaquinalmora/commitgen/cmd/commitgen@latest - -# Interactive setup -commitgen init - -# Basic usage -git add . -commitgen suggest -``` - -## πŸ“– Key Documents - -- **[SETUP.md](SETUP.md)** - Complete installation and configuration guide -- **[TECHNICAL.md](TECHNICAL.md)** - Architecture and development details -- **[CONTRIBUTING.md](CONTRIBUTING.md)** - Contribution guidelines and development workflow - -## πŸ”§ Configuration - -CommitGen supports multiple configuration methods: - -1. **Interactive setup**: `commitgen init` -2. **YAML configuration**: `commitgen.yaml` file -3. **Environment variables**: `.env` file -4. **Command line flags**: `--ai`, `--verbose`, etc. - -See [SETUP.md](SETUP.md) for detailed configuration options. - -## 🀝 Contributing - -We welcome contributions! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for: - -- Development setup -- Code style guidelines -- Testing requirements -- Pull request process - -## πŸ“‹ Project Status - -See [TODO_DEPLOYMENT.md](TODO_DEPLOYMENT.md) for current development status and deployment progress. diff --git a/DOCS/SETUP.md b/DOCS/SETUP.md index 7a50de5..49b36ff 100644 --- a/DOCS/SETUP.md +++ b/DOCS/SETUP.md @@ -45,18 +45,17 @@ This will guide you through: ### Manual Configuration -#### Environment Variables (Quick Setup) +#### Environment Variables (Alternative Setup) -Create a `.env` file: +Create a `.env` file in your home directory: ```bash -# Copy the example file -cp .env.example .env +# Generate template file +commitgen env-example +cp .env.example ~/.env -# Edit with your API key -OPENAI_API_KEY=your-api-key-here -COMMITGEN_MODEL=gpt-4o-mini -COMMITGEN_AI_ENABLED=true +# Edit with your actual API key +nano ~/.env ``` #### YAML Configuration (Advanced) @@ -217,7 +216,7 @@ commitgen install-shell # Automated setup source ~/.zshrc ``` -Manual setup for advanced users - see [DOCS/INLINE_SUGGESTIONS.md](DOCS/INLINE_SUGGESTIONS.md) for detailed instructions on oh-my-zsh + zsh-autosuggestions or plain zsh configurations. +For manual setup or advanced shell configurations, see the Shell Integration section above for detailed instructions. ## Environment Configuration diff --git a/DOCS/TECHNICAL.md b/DOCS/TECHNICAL.md deleted file mode 100644 index 224db0e..0000000 --- a/DOCS/TECHNICAL.md +++ /dev/null @@ -1,89 +0,0 @@ -# Technical Reference - -Architecture and development guide for commitgen. - -## Architecture - -```text -CLI β†’ Config β†’ Provider β†’ AI API β†’ Response - ↓ - Cache System ← Git Hooks - ↓ - Shell Integration -``` - -## Key Components - -| Component | Purpose | Location | -|-----------|---------|----------| -| **CLI** | Command routing & flags | `cmd/commitgen/main.go` | -| **Config** | Environment management | `internal/config/config.go` | -| **Providers** | AI integrations | `internal/provider/*.go` | -| **Cache** | Performance optimization | `internal/cache/cache.go` | -| **Hooks** | Git integration | `internal/hook/hook.go` | -| **Shell** | Terminal integration | `internal/shell/shell.go` | -| **Doctor** | System diagnostics | `internal/doctor/doctor.go` | - -## Provider System - -### Interface - -```go -type Provider interface { - GenerateCommitMessage(ctx context.Context, files []string, patch string) (string, error) -} -``` - -### Adding New Providers - -1. Implement `Provider` interface -2. Add to factory in `provider.go` -3. Add configuration options -4. Update documentation - -## Cache Architecture - -**Goal**: Sub-100ms commit message retrieval -**Method**: Background pre-generation via git hooks -**Storage**: Content-addressed JSON files -**Invalidation**: SHA256 hash-based change detection - -### Workflow - -1. `git add` β†’ `post-index-change` hook β†’ background cache generation -2. `git commit` β†’ `prepare-commit-msg` hook β†’ instant cache retrieval -3. Cache miss β†’ fallback to real-time AI generation - -## Performance Design - -- **Content Addressing**: Prevents duplicate AI calls for same changes -- **Background Processing**: Non-blocking cache generation -- **Graceful Degradation**: AI β†’ Cache β†’ Heuristics β†’ User input -- **Timeout Handling**: 30s AI timeout with fallback - -## Development - -### Testing - -```bash -go test ./... # Unit tests -OPENAI_API_KEY=sk-xxx go test ./e2e/... # Integration tests -commitgen doctor # System validation -``` - -### Debugging - -```bash -commitgen suggest --verbose # Debug AI generation -commitgen cache --debug # Debug cache system -ls -la .git/hooks/ # Check hook installation -``` - -### Code Style - -- Follow Go conventions (`gofmt`, `golint`) -- Add tests for new functionality -- Update docs for API changes -- Use conventional commits - -This architecture prioritizes performance, reliability, and extensibility while maintaining clean separation of concerns. diff --git a/README.md b/README.md index 97fe2c8..51f610f 100644 --- a/README.md +++ b/README.md @@ -6,76 +6,225 @@ AI-powered commit message generation for Git. Generate professional, contextual ## ⚑ Quick Start +### Installation + ```bash -# Install and setup (30 seconds) +# Option 1: Homebrew (Recommended) +brew tap joaquinalmora/tap +brew install commitgen + +# Option 2: Go Install go install github.com/joaquinalmora/commitgen/cmd/commitgen@latest -curl -sSL https://raw.githubusercontent.com/joaquinalmora/commitgen/main/scripts/setup.sh | bash -# Start using AI commit messages -git add . && git commit # AI suggestions appear automatically +# Option 3: From Source +git clone https://github.com/joaquinalmora/commitgen.git +cd commitgen && make build && make install +``` + +### Setup + +```bash +# Interactive configuration (recommended) +commitgen init + +# Add your OpenAI API key when prompted +# Then install git hooks and shell integration +commitgen install-hook +commitgen install-shell +``` + +### Basic Usage + +```bash +# Stage your changes +git add . + +# Generate AI-powered commit message +commitgen suggest --ai + +# Or just commit and get auto-suggestions +git commit -m " # AI suggestions appear here ``` ## ✨ Features - **πŸ€– AI-Powered**: OpenAI and Ollama support for professional commit messages -- **⚑ Auto-Cache**: 50x performance boost with background pre-generation +- **⚑ Auto-Cache**: Intelligent caching with 50x performance boost - **πŸ”„ Git Integration**: Automatic hooks for seamless workflow -- **οΏ½ Shell Integration**: Ghost text suggestions as you type -- **πŸ›‘οΈ Smart Fallback**: Heuristics when AI is unavailable -- **οΏ½ Zero Config**: One-command setup with intelligent defaults +- **πŸ‘» Shell Integration**: Ghost text suggestions as you type `git commit -m "` +- **πŸ›‘οΈ Smart Fallback**: Heuristic generation when AI is unavailable +- **πŸš€ Zero Config**: One-command setup with intelligent defaults +- **🎯 Context-Aware**: Analyzes actual code changes, not just file names -## πŸ“– Documentation +## πŸ”§ Configuration -- **[Complete Documentation](docs/README.md)** - Full documentation index -- **[Setup Guide](docs/SETUP.md)** - Installation, configuration, and shell integration -- **[Technical Reference](docs/TECHNICAL.md)** - Architecture and development guide -- **[Contributing](docs/CONTRIBUTING.md)** - Development guidelines and contribution process +### Environment Variables -## πŸš€ Usage +```bash +# Core configuration +OPENAI_API_KEY=sk-your-key-here +COMMITGEN_PROVIDER=openai # 'openai' or 'ollama' +COMMITGEN_MODEL=gpt-4o-mini # Model selection + +# Performance tuning +COMMITGEN_CACHE_TTL=24h # Cache lifetime +COMMITGEN_MAX_FILES=10 # Max files analyzed +COMMITGEN_PATCH_BYTES=102400 # Max patch size +``` + +### YAML Configuration + +Create `commitgen.yaml`: + +```yaml +ai: + enabled: true + provider: "openai" + model: "gpt-4o-mini" + api_key: "" # Use environment variable + +performance: + patch_bytes: 4000 + cache_ttl: "24h" + max_files: 10 + +output: + verbose: false + colors: true +``` + +## πŸš€ Usage Examples ### Basic Commands ```bash -commitgen suggest --ai # Generate AI commit message -commitgen cache # Pre-generate cache -commitgen install-hook # Setup git hooks -commitgen install-shell # Setup shell integration -commitgen doctor # Check system health +commitgen suggest # Generate commit message +commitgen suggest --ai # Force AI generation +commitgen suggest --verbose # Show detailed logs +commitgen cache # Pre-generate cache +commitgen cache --clear # Clear cache +commitgen doctor # System health check +``` + +### Git Integration + +```bash +# Install git hooks for auto-suggestions +commitgen install-hook + +# Now git commit will auto-suggest messages +git commit +# Message: "feat: add user authentication with JWT tokens" + +# Uninstall hooks +commitgen uninstall-hook +``` + +### Shell Integration + +```bash +# Install shell integration (zsh) +commitgen install-shell + +# Now typing 'git commit -m "' will show ghost text suggestions +git commit -m "feat: add user auth and↩ # <-- AI suggestion appears ``` -### AI Providers +## πŸ€– AI Providers | Provider | Best For | Setup | |----------|----------|-------| -| **OpenAI** | Production quality | Add `OPENAI_API_KEY` | -| **Ollama** | Local/private | Install Ollama + model | +| **OpenAI** | Production quality, best results | `export OPENAI_API_KEY=sk-...` | +| **Ollama** | Local/private, no API costs | Install Ollama + model | + +### OpenAI Setup + +1. Get API key from [OpenAI Platform](https://platform.openai.com/api-keys) +2. Set environment variable: `export OPENAI_API_KEY=sk-your-key` +3. Optional: Choose model: `export COMMITGEN_MODEL=gpt-4o-mini` + +### Ollama Setup + +1. Install [Ollama](https://ollama.ai) +2. Pull a model: `ollama pull llama3.2:3b` +3. Configure: `export COMMITGEN_PROVIDER=ollama COMMITGEN_MODEL=llama3.2:3b` + +## πŸ› οΈ Troubleshooting + +### Common Issues + +**"No API key" error:** + +- Run `commitgen init` for interactive setup +- Set `OPENAI_API_KEY` environment variable +- Verify API key at OpenAI platform + +**"Not a git repository" error:** + +- Ensure you're in a git repository (`git init` if needed) +- Check current directory with `pwd` + +**"No staged changes" error:** -### Configuration +- Stage files first: `git add ` +- Check status: `git status` + +**Shell integration not working:** + +- Run `commitgen doctor` for diagnostics +- Reinstall: `commitgen uninstall-shell && commitgen install-shell` +- Source shell: `source ~/.zshrc` + +### Debug Mode ```bash -# Quick config via environment -export OPENAI_API_KEY="sk-your-key" -export COMMITGEN_PROVIDER="openai" # or "ollama" -export COMMITGEN_MODEL="gpt-4o-mini" # or "llama3.2:3b" +commitgen suggest --verbose # Show detailed logs +commitgen doctor # System diagnostics ``` ## 🎯 How It Works -1. **Stage changes**: `git add .` -2. **AI generates**: Background cache or real-time -3. **Shell suggests**: Ghost text appears as you type -4. **Accept/commit**: Press β†’ or just commit normally +1. **Analyze Changes**: Reads git staged changes and file modifications +2. **Generate Context**: Creates intelligent prompts from code diffs +3. **AI Processing**: Sends context to AI provider (OpenAI/Ollama) +4. **Smart Caching**: Caches results for identical changes +5. **Integration**: Provides suggestions via git hooks or shell integration + +## πŸ“š Documentation + +- **[Setup Guide](docs/SETUP.md)** - Complete installation and configuration +- **[Technical Reference](docs/TECHNICAL.md)** - Architecture and development +- **[Contributing Guide](docs/CONTRIBUTING.md)** - Development guidelines +- **[Changelog](docs/CHANGELOG.md)** - Release history ## 🀝 Contributing -1. Fork and create feature branch -2. Make changes with tests -3. Submit pull request +1. Fork the repository +2. Create a feature branch: `git checkout -b feature/amazing-feature` +3. Make changes with tests +4. Submit a pull request -See [DOCS/TECHNICAL.md](DOCS/TECHNICAL.md) for architecture details. +See [docs/CONTRIBUTING.md](docs/CONTRIBUTING.md) for detailed guidelines. -## πŸ“„ License +## οΏ½ Uninstall + +Complete removal: -MIT License - see LICENSE file for details. +```bash +# Remove integrations +commitgen uninstall-shell +commitgen uninstall-hook # Run in each repository + +# Remove binary (if installed manually) +sudo rm /usr/local/bin/commitgen + +# Or via Homebrew +brew uninstall commitgen + +# Clean up configuration +rm ~/.env ~/.config/commitgen.zsh +``` + +## πŸ“„ License MIT License - see [LICENSE](LICENSE) file for details. diff --git a/cmd/commitgen/main.go b/cmd/commitgen/main.go index 5cea0b3..6e7b55a 100644 --- a/cmd/commitgen/main.go +++ b/cmd/commitgen/main.go @@ -113,6 +113,12 @@ var commands = map[string]Command{ initConfig(args) }, }, + "env-example": { + Description: "Generate .env.example template file", + Run: func(args []string) { + generateEnvExample(args) + }, + }, "uninstall-shell": { Description: "Remove shell snippet and guarded .zshrc block", Run: func(args []string) { @@ -511,3 +517,38 @@ advanced: fmt.Println("2. Customize the configuration as needed") fmt.Println("3. Run 'commitgen suggest' to test your setup") } + +func generateEnvExample(args []string) { + filename := ".env.example" + if len(args) > 0 { + filename = args[0] + } + + content := `# commitgen Environment Configuration +# Copy this file to .env and add your actual API keys + +# OpenAI Configuration (Primary AI Provider) +# Get your API key from: https://platform.openai.com/api-keys +OPENAI_API_KEY=your-openai-api-key-here + +# Optional: Override default model (gpt-4o-mini) +# COMMITGEN_MODEL=gpt-4o + +# Performance Tuning (optional) +# COMMITGEN_CACHE_TTL=24h +# COMMITGEN_MAX_FILES=10 +# COMMITGEN_PATCH_BYTES=102400 + +# Advanced Options (optional) +# COMMITGEN_AI_FALLBACK=true +# COMMITGEN_CONVENTIONS_FILE=/path/to/custom-conventions.md +` + + if err := os.WriteFile(filename, []byte(content), 0644); err != nil { + fmt.Printf("❌ Failed to create %s: %v\n", filename, err) + os.Exit(1) + } + + fmt.Printf("βœ… Created %s\n", filename) + fmt.Println("Edit this file with your actual API key, then copy to .env") +} diff --git a/internal/provider/openai.go b/internal/provider/openai.go index 0cf7663..7802196 100644 --- a/internal/provider/openai.go +++ b/internal/provider/openai.go @@ -196,7 +196,19 @@ func (p *OpenAIProvider) GenerateCommitMessage(ctx context.Context, files []stri } if len(result) > 0 { - message = strings.Join(result, " ") + truncated := strings.Join(result, " ") + // Check if the last word is a connector word that suggests incomplete thought + lastWord := strings.ToLower(result[len(result)-1]) + if lastWord == "and" || lastWord == "or" || lastWord == "but" || lastWord == "with" || lastWord == "for" || lastWord == "to" { + // Remove the connector word to avoid incomplete sentences + if len(result) > 1 { + truncated = strings.Join(result[:len(result)-1], " ") + } else { + // If only connector word, fall back to character truncation + truncated = firstLine[:69] + "..." + } + } + message = truncated } else { message = firstLine[:69] + "..." } diff --git a/scripts/setup.sh b/scripts/setup.sh index 4b57e2c..eca530b 100755 --- a/scripts/setup.sh +++ b/scripts/setup.sh @@ -1,5 +1,5 @@ #!/bin/bash -# commitgen setup script - makes AI setup simple for users +# commitgen automated setup script set -e @@ -7,43 +7,71 @@ echo "πŸš€ Setting up commitgen with AI..." # Check if commitgen is installed if ! command -v commitgen &> /dev/null; then - echo "❌ commitgen not found. Please install first:" - echo " brew install joaquinalmora/tap/commitgen" - exit 1 + echo "❌ commitgen not found. Installing via go install..." + if ! command -v go &> /dev/null; then + echo "❌ Go not found. Please install Go first or use Homebrew:" + echo " brew tap joaquinalmora/tap && brew install commitgen" + exit 1 + fi + go install github.com/joaquinalmora/commitgen/cmd/commitgen@latest + echo "βœ… commitgen installed" fi -# Copy environment template -if [ ! -f ~/.env ]; then - echo "πŸ“ Creating environment template..." - cp .env.example ~/.env - echo "βœ… Created ~/.env file" +# Ask user preference for configuration method +echo "" +echo "Choose configuration method:" +echo "1. Interactive setup (recommended) - creates commitgen.yaml" +echo "2. Environment variables - creates .env file" +read -p "Enter choice [1-2] (default: 1): " config_choice + +if [[ "$config_choice" == "2" ]]; then + # Environment variables setup + echo "πŸ“ Setting up environment variables..." + commitgen env-example + if [[ -f .env.example ]]; then + cp .env.example ~/.env + echo "βœ… Created ~/.env file" + echo "" + echo "πŸ”‘ NEXT STEP: Add your OpenAI API key" + echo " 1. Get API key: https://platform.openai.com/api-keys" + echo " 2. Edit: nano ~/.env" + echo " 3. Replace: your-openai-api-key-here" + echo "" + read -p "Press Enter when you've added your API key..." + fi else - echo "πŸ“ ~/.env already exists" + # Interactive setup (default) + echo "πŸ“ Starting interactive configuration..." + commitgen init fi -# Check for API key -if grep -q "your-openai-api-key-here" ~/.env 2>/dev/null; then - echo "" - echo "πŸ”‘ NEXT STEP: Add your OpenAI API key" - echo " 1. Get API key: https://platform.openai.com/api-keys" - echo " 2. Edit: nano ~/.env" - echo " 3. Replace: your-openai-api-key-here" - echo "" - read -p "Press Enter when you've added your API key..." +# Install integrations +echo "πŸ”§ Installing git hooks..." +if git rev-parse --git-dir >/dev/null 2>&1; then + commitgen install-hook + echo "βœ… Git hooks installed" +else + echo "⚠️ Not in a git repository. Git hooks will be installed per-repo later." fi -# Install shell integration echo "πŸ”§ Installing shell integration..." commitgen install-shell +echo "βœ… Shell integration installed" -# Test AI -echo "πŸ€– Testing AI connection..." -if commitgen suggest --ai >/dev/null 2>&1; then - echo "βœ… AI is working!" +# Test the setup +echo "πŸ€– Testing configuration..." +if commitgen doctor >/dev/null 2>&1; then + echo "βœ… All checks passed!" else - echo "⚠️ AI test failed. Check your API key in ~/.env" + echo "⚠️ Some checks failed. Run 'commitgen doctor' for details." fi echo "" -echo "πŸŽ‰ Setup complete! Try typing: git commit -m \"" -echo " AI suggestions will appear automatically!" +echo "πŸŽ‰ Setup complete!" +echo "" +echo "Next steps:" +echo "1. Restart your terminal or run: source ~/.zshrc" +echo "2. In a git repo, try: git add . && git commit -m \"" +echo "3. AI suggestions will appear automatically!" +echo "" +echo "Troubleshooting: run 'commitgen doctor' for diagnostics"