# Git Workflow & Version Control

## Git Workflow Checklist

- [ ] Use feature branches for all development ([Branch Structure](#branch-structure))
- [ ] Follow conventional commit format ([Conventional Commits](#conventional-commits))
- [ ] Squash merge features to develop ([Merge Strategy](#merge-strategy))
- [ ] Protect main branch from direct commits ([Protected Branches](#protected-branches))
- [ ] Review all code before merging ([Code Review Guidelines](#code-review-guidelines))
- [ ] Use merge commits for releases ([Quick Release Process](#quick-release-process))
- [ ] Tag releases consistently ([Quick Release Process](#quick-release-process))
- [ ] Set up pre-commit hooks ([Pre-commit Hooks](#pre-commit-hooks))
- [ ] Configure CI/CD pipeline ([CI/CD Integration](#cicd-integration))
- [ ] Use meaningful branch names ([Branch Structure](#branch-structure))
- [ ] Write clear commit messages ([Conventional Commits](#conventional-commits))
- [ ] Reference issues in commits ([Conventional Commits](#conventional-commits))
- [ ] Clean up merged branches ([Daily Operations](#daily-operations))
- [ ] Keep commit history clean ([Merge Strategy](#merge-strategy))

## Branching Strategy

### Branch Structure
Keep it simple for small teams.

**Why:** A simplified Git flow reduces complexity while maintaining code quality. For MVPs with AI-assisted development, you need just enough process to prevent conflicts without slowing down shipping.

```bash
main            # Production-ready code
├── develop     # Integration branch for features
├── feature/*   # Feature development
├── hotfix/*    # Emergency production fixes
└── release/*   # Release preparation (optional for MVP)

# Branch naming conventions
feature/add-payment-integration
feature/fix-user-auth
hotfix/critical-security-patch
release/v1.2.0

# Create feature branch
git checkout -b feature/add-stripe-payment develop

# Create hotfix
git checkout -b hotfix/fix-memory-leak main
```

### Merge Strategy
Keep history clean and traceable.

**Why:** Clean Git history makes debugging easier, helps understand code evolution, and simplifies rollbacks when things go wrong.

```bash
# Feature to develop: Squash merge (clean history)
git checkout develop
git merge --squash feature/add-payment
git commit -m "feat: add Stripe payment integration (#123)"

# Develop to main: Merge commit (preserve context)
git checkout main
git merge --no-ff develop -m "Release v1.2.0"

# Hotfix to main: Direct merge
git checkout main
git merge hotfix/fix-memory-leak
git checkout develop
git merge hotfix/fix-memory-leak  # Don't forget develop!
```

## Commit Standards

### Conventional Commits
Use consistent, semantic commit messages.

**Why:** Structured commits enable automatic changelog generation, make history searchable, and communicate intent clearly to both humans and AI assistants.

```bash
# Format: <type>(<scope>): <subject>

# Types
feat:     # New feature
fix:      # Bug fix
docs:     # Documentation changes
style:    # Code style changes (formatting, semicolons, etc)
refactor: # Code refactoring without feature changes
perf:     # Performance improvements
test:     # Test additions or fixes
chore:    # Build tasks, dependencies, etc
revert:   # Revert a previous commit

# Examples
feat(auth): add OAuth2 Google login
fix(api): handle null response from payment service
docs(readme): update installation instructions
perf(db): add index on users.email column
test(user): add integration tests for registration

# Breaking changes
feat(api)!: change user endpoint response format

BREAKING CHANGE: The user endpoint now returns nested
data instead of flat structure. Update clients accordingly.

# Multi-line for complex changes
fix(cart): resolve race condition in checkout

- Add mutex lock during payment processing
- Prevent double-charging on rapid clicks
- Add integration test for concurrent checkouts

Fixes #456
```

### Code Review Guidelines
Review all code thoroughly before committing.

**Why:** Whether human-written or AI-generated, all code needs review to catch errors, ensure consistency, and maintain quality standards.

```bash
# Review changes carefully before committing
git add -p  # Stage changes interactively
git diff --staged  # Review staged changes
git status  # Verify what's being committed

# Write clear commit messages explaining the "why"
feat(dashboard): add analytics charts

- Implemented daily/weekly/monthly view toggles
- Added error boundaries for data fetch failures
- Integrated with existing theme system

# For complex changes, provide context
refactor(api): optimize database queries

Replaced N+1 queries with batched DataLoader pattern.
Reduces average response time from 800ms to 150ms.
```

## Workflow Rules

### Protected Branches
Never commit directly to main.

**Why:** Protected branches prevent accidental breaks in production, enforce code review (even for solo developers reviewing AI code), and maintain deployment stability.

```bash
# GitHub branch protection settings (minimum for MVP)
main:
  - Require pull request before merging
  - Dismiss stale reviews on new commits
  - Require branches to be up to date (optional for speed)
  - Include administrators (yes, even you)

develop:
  - Require pull request for external contributors
  - No force push allowed
```

### Pull Request Process
Quick reviews for fast shipping.

**Why:** Even minimal PR review catches obvious errors, documents changes, and creates a checkpoint before merging AI-generated code.

```markdown
## PR Template (.github/pull_request_template.md)

### What does this PR do?
Brief description of changes

### Type of change
- [ ] Bug fix
- [ ] New feature
- [ ] Breaking change
- [ ] Documentation

### Checklist
- [ ] Code runs locally
- [ ] Tests pass
- [ ] No console errors

### Screenshots (if UI changes)
[Add screenshots]
```

### Quick Release Process
Ship fast but safely.

**Why:** MVPs need to iterate quickly. This minimal process ensures you can deploy anytime while maintaining basic safety checks.

```bash
# 1. Ensure develop is stable
git checkout develop
npm test
npm run build

# 2. Create release (optional for MVP)
git checkout -b release/v1.2.0 develop
# Update version in package.json
git commit -m "chore: bump version to 1.2.0"

# 3. Merge to main
git checkout main
git merge --no-ff release/v1.2.0
git tag -a v1.2.0 -m "Release version 1.2.0"

# 4. Deploy (automatic via CI/CD)
git push origin main --tags

# 5. Back-merge to develop
git checkout develop
git merge main
```

## Essential Git Commands

### Daily Operations
Commands you'll use every day.

```bash
# Start new work
git checkout develop
git pull origin develop
git checkout -b feature/new-feature

# Save work in progress
git stash  # Temporarily save changes
git stash pop  # Restore changes

# Check what you're about to commit
git diff  # Unstaged changes
git diff --staged  # Staged changes
git status -s  # Short status

# Undo mistakes
git reset HEAD~1  # Undo last commit, keep changes
git reset --hard HEAD~1  # Undo last commit, discard changes
git checkout -- file.js  # Discard changes to specific file

# Clean up
git branch -D feature/old-feature  # Delete local branch
git remote prune origin  # Clean up deleted remote branches
```

### Emergency Procedures
When things go wrong.

**Why:** Everyone makes mistakes. These commands help recover from common Git disasters without losing work.

```bash
# Accidentally committed to main
git reset HEAD~1  # Undo commit
git stash  # Save changes
git checkout develop
git checkout -b feature/proper-branch
git stash pop

# Need to undo a pushed commit
git revert <commit-hash>  # Creates new commit that undoes changes
git push

# Lost commits after reset
git reflog  # Shows all recent operations
git checkout <lost-commit-hash>

# Merge conflicts
git status  # See conflicted files
# Fix conflicts in editor, then:
git add <resolved-files>
git commit

# Nuclear option: start fresh
git fetch origin
git reset --hard origin/develop  # WARNING: Loses all local changes
```

## Hooks and Automation

### Pre-commit Hooks
Catch issues before they're committed.

```json
// package.json
{
  "husky": {
    "hooks": {
      "pre-commit": "npm run lint:staged && npm run type-check",
      "commit-msg": "commitlint -E HUSKY_GIT_PARAMS",
      "pre-push": "npm test"
    }
  },
  "lint-staged": {
    "*.{ts,tsx}": ["eslint --fix", "git add"],
    "*.{json,md}": ["prettier --write", "git add"]
  }
}
```

### CI/CD Integration
Automate everything possible.

```yaml
# .github/workflows/main.yml (simplified)
on:
  push:
    branches: [main, develop]
  pull_request:
    branches: [main]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - run: npm ci
      - run: npm test
      - run: npm run build

  deploy:
    if: github.ref == 'refs/heads/main'
    needs: test
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - run: npm ci
      - run: npm run build
      - run: npm run deploy
```

## Git Configuration

### Essential Setup
Configure Git for productivity.

```bash
# Identity
git config --global user.name "Your Name"
git config --global user.email "you@example.com"

# Helpful aliases
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
git config --global alias.st status
git config --global alias.last 'log -1 HEAD'
git config --global alias.unstage 'reset HEAD --'
git config --global alias.visual 'log --oneline --graph --all'

# Better diffs
git config --global diff.algorithm histogram
git config --global merge.conflictstyle diff3

# Default branch name
git config --global init.defaultBranch main

# Auto-prune on fetch
git config --global fetch.prune true
```

## Quick Reference

### Branch Workflow
```
main (production) ← develop ← feature/*
      ↑                          ↓
      └──────── hotfix/* ────────┘
```

### Commit Types
- `feat:` New feature
- `fix:` Bug fix
- `docs:` Documentation
- `test:` Tests
- `refactor:` Code refactoring
- `chore:` Maintenance

### Daily Flow
1. Pull latest: `git pull origin develop`
2. Create branch: `git checkout -b feature/name`
3. Make changes & commit often
4. Push: `git push -u origin feature/name`
5. Create PR
6. Merge and delete branch