add brain

This commit is contained in:
2026-03-12 15:17:52 +07:00
parent fd9f558fa1
commit e7821a7a9d
355 changed files with 93784 additions and 24 deletions

View File

@@ -0,0 +1,341 @@
# Conventional Commits Guide
## Overview
Conventional Commits is a specification for adding human and machine readable meaning to commit messages. The specification provides an easy set of rules for creating an explicit commit history, which makes it easier to write automated tools for version management, changelog generation, and release planning.
## Basic Format
```
<type>[optional scope]: <description>
[optional body]
[optional footer(s)]
```
## Commit Types
### Primary Types
- **feat**: A new feature for the user (correlates with MINOR in semantic versioning)
- **fix**: A bug fix for the user (correlates with PATCH in semantic versioning)
### Secondary Types
- **build**: Changes that affect the build system or external dependencies (webpack, npm, etc.)
- **ci**: Changes to CI configuration files and scripts (Travis, Circle, BrowserStack, SauceLabs)
- **docs**: Documentation only changes
- **perf**: A code change that improves performance
- **refactor**: A code change that neither fixes a bug nor adds a feature
- **style**: Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc.)
- **test**: Adding missing tests or correcting existing tests
- **chore**: Other changes that don't modify src or test files
- **revert**: Reverts a previous commit
### Breaking Changes
Any commit can introduce a breaking change by:
1. Adding `!` after the type: `feat!: remove deprecated API`
2. Including `BREAKING CHANGE:` in the footer
## Scopes
Scopes provide additional contextual information about the change. They should be noun describing a section of the codebase:
- `auth` - Authentication and authorization
- `api` - API changes
- `ui` - User interface
- `db` - Database related changes
- `config` - Configuration changes
- `deps` - Dependency updates
## Examples
### Simple Feature
```
feat(auth): add OAuth2 integration
Integrate OAuth2 authentication with Google and GitHub providers.
Users can now log in using their existing social media accounts.
```
### Bug Fix
```
fix(api): resolve race condition in user creation
When multiple requests tried to create users with the same email
simultaneously, duplicate records were sometimes created. Added
proper database constraints and error handling.
Fixes #234
```
### Breaking Change with !
```
feat(api)!: remove deprecated /v1/users endpoint
The deprecated /v1/users endpoint has been removed. All clients
should migrate to /v2/users which provides better performance
and additional features.
BREAKING CHANGE: /v1/users endpoint removed, use /v2/users instead
```
### Breaking Change with Footer
```
feat(auth): implement new authentication flow
Add support for multi-factor authentication and improved session
management. This change requires all users to re-authenticate.
BREAKING CHANGE: Authentication tokens issued before this release
are no longer valid. Users must log in again.
```
### Performance Improvement
```
perf(image): optimize image compression algorithm
Replaced PNG compression with WebP format, reducing image sizes
by 40% on average while maintaining visual quality.
Closes #456
```
### Dependency Update
```
build(deps): upgrade React to version 18.2.0
Updates React and related packages to latest stable versions.
Includes performance improvements and new concurrent features.
```
### Documentation
```
docs(readme): add deployment instructions
Added comprehensive deployment guide including Docker setup,
environment variables configuration, and troubleshooting tips.
```
### Revert
```
revert: feat(payment): add cryptocurrency support
This reverts commit 667ecc1654a317a13331b17617d973392f415f02.
Reverting due to security concerns identified in code review.
The feature will be re-implemented with proper security measures.
```
## Multi-paragraph Body
For complex changes, use multiple paragraphs in the body:
```
feat(search): implement advanced search functionality
Add support for complex search queries including:
- Boolean operators (AND, OR, NOT)
- Field-specific searches (title:, author:, date:)
- Fuzzy matching with configurable threshold
- Search result highlighting
The search index has been restructured to support these new
features while maintaining backward compatibility with existing
simple search queries.
Performance testing shows less than 10ms impact on search
response times even with complex queries.
Closes #789, #823, #901
```
## Footers
### Issue References
```
Fixes #123
Closes #234, #345
Resolves #456
```
### Breaking Changes
```
BREAKING CHANGE: The `authenticate` function now requires a second
parameter for the authentication method. Update all calls from
`authenticate(token)` to `authenticate(token, 'bearer')`.
```
### Co-authors
```
Co-authored-by: Jane Doe <jane@example.com>
Co-authored-by: John Smith <john@example.com>
```
### Reviewed By
```
Reviewed-by: Senior Developer <senior@example.com>
Acked-by: Tech Lead <lead@example.com>
```
## Automation Benefits
Using conventional commits enables:
### Automatic Version Bumping
- `fix` commits trigger PATCH version bump (1.0.0 → 1.0.1)
- `feat` commits trigger MINOR version bump (1.0.0 → 1.1.0)
- `BREAKING CHANGE` triggers MAJOR version bump (1.0.0 → 2.0.0)
### Changelog Generation
```markdown
## [1.2.0] - 2024-01-15
### Added
- OAuth2 integration (auth)
- Advanced search functionality (search)
### Fixed
- Race condition in user creation (api)
- Memory leak in image processing (image)
### Breaking Changes
- Authentication tokens issued before this release are no longer valid
```
### Release Notes
Generate user-friendly release notes automatically from commit history, filtering out internal changes and highlighting user-facing improvements.
## Best Practices
### Writing Good Descriptions
- Use imperative mood: "add feature" not "added feature"
- Start with lowercase letter
- No period at the end
- Limit to 50 characters when possible
- Be specific and descriptive
### Good Examples
```
feat(auth): add password reset functionality
fix(ui): resolve mobile navigation menu overflow
perf(db): optimize user query with proper indexing
```
### Bad Examples
```
feat: stuff
fix: bug
update: changes
```
### Body Guidelines
- Separate subject from body with blank line
- Wrap body at 72 characters
- Use body to explain what and why, not how
- Reference issues and PRs when relevant
### Scope Guidelines
- Use consistent scope naming across the team
- Keep scopes short and meaningful
- Document your team's scope conventions
- Consider using scopes that match your codebase structure
## Tools and Integration
### Git Hooks
Use tools like `commitizen` or `husky` to enforce conventional commit format:
```bash
# Install commitizen
npm install -g commitizen cz-conventional-changelog
# Configure
echo '{ "path": "cz-conventional-changelog" }' > ~/.czrc
# Use
git cz
```
### Automated Validation
Add commit message validation to prevent non-conventional commits:
```javascript
// commitlint.config.js
module.exports = {
extends: ['@commitlint/config-conventional'],
rules: {
'type-enum': [
2, 'always',
['feat', 'fix', 'docs', 'style', 'refactor', 'perf', 'test', 'build', 'ci', 'chore', 'revert']
],
'subject-case': [2, 'always', 'lower-case'],
'subject-max-length': [2, 'always', 50]
}
};
```
### CI/CD Integration
Integrate with release automation tools:
- **semantic-release**: Automated version management and package publishing
- **standard-version**: Generate changelog and tag releases
- **release-please**: Google's release automation tool
## Common Mistakes
### Mixing Multiple Changes
```
# Bad: Multiple unrelated changes
feat: add login page and fix CSS bug and update dependencies
# Good: Separate commits
feat(auth): add login page
fix(ui): resolve CSS styling issue
build(deps): update React to version 18
```
### Vague Descriptions
```
# Bad: Not descriptive
fix: bug in code
feat: new stuff
# Good: Specific and clear
fix(api): resolve null pointer exception in user validation
feat(search): implement fuzzy matching algorithm
```
### Missing Breaking Change Indicators
```
# Bad: Breaking change not marked
feat(api): update user authentication
# Good: Properly marked breaking change
feat(api)!: update user authentication
BREAKING CHANGE: All API clients must now include authentication
headers in every request. Anonymous access is no longer supported.
```
## Team Guidelines
### Establishing Conventions
1. **Define scope vocabulary**: Create a list of approved scopes for your project
2. **Document examples**: Provide team-specific examples of good commits
3. **Set up tooling**: Use linters and hooks to enforce standards
4. **Review process**: Include commit message quality in code reviews
5. **Training**: Ensure all team members understand the format
### Scope Examples by Project Type
**Web Application:**
- `auth`, `ui`, `api`, `db`, `config`, `deploy`
**Library/SDK:**
- `core`, `utils`, `docs`, `examples`, `tests`
**Mobile App:**
- `ios`, `android`, `shared`, `ui`, `network`, `storage`
By following conventional commits consistently, your team will have a clear, searchable commit history that enables powerful automation and improves the overall development workflow.

View File

@@ -0,0 +1,592 @@
# Hotfix Procedures
## Overview
Hotfixes are emergency releases designed to address critical production issues that cannot wait for the regular release cycle. This document outlines classification, procedures, and best practices for managing hotfixes across different development workflows.
## Severity Classification
### P0 - Critical (Production Down)
**Definition:** Complete system outage, data corruption, or security breach affecting all users.
**Examples:**
- Server crashes preventing any user access
- Database corruption causing data loss
- Security vulnerability being actively exploited
- Payment system completely non-functional
- Authentication system failure preventing all logins
**Response Requirements:**
- **Timeline:** Fix deployed within 2 hours
- **Approval:** Engineering Lead + On-call Manager (verbal approval acceptable)
- **Process:** Emergency deployment bypassing normal gates
- **Communication:** Immediate notification to all stakeholders
- **Documentation:** Post-incident review required within 24 hours
**Escalation:**
- Page on-call engineer immediately
- Escalate to Engineering Lead within 15 minutes
- Notify CEO/CTO if resolution exceeds 4 hours
### P1 - High (Major Feature Broken)
**Definition:** Critical functionality broken affecting significant portion of users.
**Examples:**
- Core user workflow completely broken
- Payment processing failures affecting >50% of transactions
- Search functionality returning no results
- Mobile app crashes on startup
- API returning 500 errors for main endpoints
**Response Requirements:**
- **Timeline:** Fix deployed within 24 hours
- **Approval:** Engineering Lead + Product Manager
- **Process:** Expedited review and testing
- **Communication:** Stakeholder notification within 1 hour
- **Documentation:** Root cause analysis within 48 hours
**Escalation:**
- Notify on-call engineer within 30 minutes
- Escalate to Engineering Lead within 2 hours
- Daily updates to Product/Business stakeholders
### P2 - Medium (Minor Feature Issues)
**Definition:** Non-critical functionality issues with limited user impact.
**Examples:**
- Cosmetic UI issues affecting user experience
- Non-essential features not working properly
- Performance degradation not affecting core workflows
- Minor API inconsistencies
- Reporting/analytics data inaccuracies
**Response Requirements:**
- **Timeline:** Include in next regular release
- **Approval:** Standard pull request review process
- **Process:** Normal development and testing cycle
- **Communication:** Include in regular release notes
- **Documentation:** Standard issue tracking
**Escalation:**
- Create ticket in normal backlog
- No special escalation required
- Include in release planning discussions
## Hotfix Workflows by Development Model
### Git Flow Hotfix Process
#### Branch Structure
```
main (v1.2.3) ← hotfix/security-patch → main (v1.2.4)
→ develop
```
#### Step-by-Step Process
1. **Create Hotfix Branch**
```bash
git checkout main
git pull origin main
git checkout -b hotfix/security-patch
```
2. **Implement Fix**
- Make minimal changes addressing only the specific issue
- Include tests to prevent regression
- Update version number (patch increment)
```bash
# Fix the issue
git add .
git commit -m "fix: resolve SQL injection vulnerability"
# Version bump
echo "1.2.4" > VERSION
git add VERSION
git commit -m "chore: bump version to 1.2.4"
```
3. **Test Fix**
- Run automated test suite
- Manual testing of affected functionality
- Security review if applicable
```bash
# Run tests
npm test
python -m pytest
# Security scan
npm audit
bandit -r src/
```
4. **Deploy to Staging**
```bash
# Deploy hotfix branch to staging
git push origin hotfix/security-patch
# Trigger staging deployment via CI/CD
```
5. **Merge to Production**
```bash
# Merge to main
git checkout main
git merge --no-ff hotfix/security-patch
git tag -a v1.2.4 -m "Hotfix: Security vulnerability patch"
git push origin main --tags
# Merge back to develop
git checkout develop
git merge --no-ff hotfix/security-patch
git push origin develop
# Clean up
git branch -d hotfix/security-patch
git push origin --delete hotfix/security-patch
```
### GitHub Flow Hotfix Process
#### Branch Structure
```
main ← hotfix/critical-fix → main (immediate deploy)
```
#### Step-by-Step Process
1. **Create Fix Branch**
```bash
git checkout main
git pull origin main
git checkout -b hotfix/payment-gateway-fix
```
2. **Implement and Test**
```bash
# Make the fix
git add .
git commit -m "fix(payment): resolve gateway timeout issue"
git push origin hotfix/payment-gateway-fix
```
3. **Create Emergency PR**
```bash
# Use GitHub CLI or web interface
gh pr create --title "HOTFIX: Payment gateway timeout" \
--body "Critical fix for payment processing failures" \
--reviewer engineering-team \
--label hotfix
```
4. **Deploy Branch for Testing**
```bash
# Deploy branch to staging for validation
./deploy.sh hotfix/payment-gateway-fix staging
# Quick smoke tests
```
5. **Emergency Merge and Deploy**
```bash
# After approval, merge and deploy
gh pr merge --squash
# Automatic deployment to production via CI/CD
```
### Trunk-based Hotfix Process
#### Direct Commit Approach
```bash
# For small fixes, commit directly to main
git checkout main
git pull origin main
# Make fix
git add .
git commit -m "fix: resolve memory leak in user session handling"
git push origin main
# Automatic deployment triggers
```
#### Feature Flag Rollback
```bash
# For feature-related issues, disable via feature flag
curl -X POST api/feature-flags/new-search/disable
# Verify issue resolved
# Plan proper fix for next deployment
```
## Emergency Response Procedures
### Incident Declaration Process
1. **Detection and Assessment** (0-5 minutes)
- Monitor alerts or user reports identify issue
- Assess severity using classification matrix
- Determine if hotfix is required
2. **Team Assembly** (5-10 minutes)
- Page appropriate on-call engineer
- Assemble incident response team
- Establish communication channel (Slack, Teams)
3. **Initial Response** (10-30 minutes)
- Create incident ticket/document
- Begin investigating root cause
- Implement immediate mitigations if possible
4. **Hotfix Development** (30 minutes - 2 hours)
- Create hotfix branch
- Implement minimal fix
- Test fix in isolation
5. **Deployment** (15-30 minutes)
- Deploy to staging for validation
- Deploy to production
- Monitor for successful resolution
6. **Verification** (15-30 minutes)
- Confirm issue is resolved
- Monitor system stability
- Update stakeholders
### Communication Templates
#### P0 Initial Alert
```
🚨 CRITICAL INCIDENT - Production Down
Status: Investigating
Impact: Complete service outage
Affected Users: All users
Started: 2024-01-15 14:30 UTC
Incident Commander: @john.doe
Current Actions:
- Investigating root cause
- Preparing emergency fix
- Will update every 15 minutes
Status Page: https://status.ourapp.com
Incident Channel: #incident-2024-001
```
#### P0 Resolution Notice
```
✅ RESOLVED - Production Restored
Status: Resolved
Resolution Time: 1h 23m
Root Cause: Database connection pool exhaustion
Fix: Increased connection limits and restarted services
Timeline:
14:30 UTC - Issue detected
14:45 UTC - Root cause identified
15:20 UTC - Fix deployed
15:35 UTC - Full functionality restored
Post-incident review scheduled for tomorrow 10:00 AM.
Thank you for your patience.
```
#### P1 Status Update
```
⚠️ Issue Update - Payment Processing
Status: Fix deployed, monitoring
Impact: Payment failures reduced from 45% to <2%
ETA: Complete resolution within 2 hours
Actions taken:
- Deployed hotfix to address timeout issues
- Increased monitoring on payment gateway
- Contacting affected customers
Next update in 30 minutes or when resolved.
```
### Rollback Procedures
#### When to Rollback
- Fix doesn't resolve the issue
- Fix introduces new problems
- System stability is compromised
- Data corruption is detected
#### Rollback Process
1. **Immediate Assessment** (2-5 minutes)
```bash
# Check system health
curl -f https://api.ourapp.com/health
# Review error logs
kubectl logs deployment/app --tail=100
# Check key metrics
```
2. **Rollback Execution** (5-15 minutes)
```bash
# Git-based rollback
git checkout main
git revert HEAD
git push origin main
# Or container-based rollback
kubectl rollout undo deployment/app
# Or load balancer switch
aws elbv2 modify-target-group --target-group-arn arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/previous-version
```
3. **Verification** (5-10 minutes)
```bash
# Confirm rollback successful
# Check system health endpoints
# Verify core functionality working
# Monitor error rates and performance
```
4. **Communication**
```
🔄 ROLLBACK COMPLETE
The hotfix has been rolled back due to [reason].
System is now stable on previous version.
We are investigating the issue and will provide updates.
```
## Testing Strategies for Hotfixes
### Pre-deployment Testing
#### Automated Testing
```bash
# Run full test suite
npm test
pytest tests/
go test ./...
# Security scanning
npm audit --audit-level high
bandit -r src/
gosec ./...
# Integration tests
./run_integration_tests.sh
# Load testing (if performance-related)
artillery quick --count 100 --num 10 https://staging.ourapp.com
```
#### Manual Testing Checklist
- [ ] Core user workflow functions correctly
- [ ] Authentication and authorization working
- [ ] Payment processing (if applicable)
- [ ] Data integrity maintained
- [ ] No new error logs or exceptions
- [ ] Performance within acceptable range
- [ ] Mobile app functionality (if applicable)
- [ ] Third-party integrations working
#### Staging Validation
```bash
# Deploy to staging
./deploy.sh hotfix/critical-fix staging
# Run smoke tests
curl -f https://staging.ourapp.com/api/health
./smoke_tests.sh
# Manual verification of specific issue
# Document test results
```
### Post-deployment Monitoring
#### Immediate Monitoring (First 30 minutes)
- Error rate and count
- Response time and latency
- CPU and memory usage
- Database connection counts
- Key business metrics
#### Extended Monitoring (First 24 hours)
- User activity patterns
- Feature usage statistics
- Customer support tickets
- Performance trends
- Security log analysis
#### Monitoring Scripts
```bash
#!/bin/bash
# monitor_hotfix.sh - Post-deployment monitoring
echo "=== Hotfix Deployment Monitoring ==="
echo "Deployment time: $(date)"
echo
# Check application health
echo "--- Application Health ---"
curl -s https://api.ourapp.com/health | jq '.'
# Check error rates
echo "--- Error Rates (last 30min) ---"
curl -s "https://api.datadog.com/api/v1/query?query=sum:application.errors{*}" \
-H "DD-API-KEY: $DATADOG_API_KEY" | jq '.series[0].pointlist[-1][1]'
# Check response times
echo "--- Response Times ---"
curl -s "https://api.datadog.com/api/v1/query?query=avg:application.response_time{*}" \
-H "DD-API-KEY: $DATADOG_API_KEY" | jq '.series[0].pointlist[-1][1]'
# Check database connections
echo "--- Database Status ---"
psql -h db.ourapp.com -U readonly -c "SELECT count(*) as active_connections FROM pg_stat_activity;"
echo "=== Monitoring Complete ==="
```
## Documentation and Learning
### Incident Documentation Template
```markdown
# Incident Report: [Brief Description]
## Summary
- **Incident ID:** INC-2024-001
- **Severity:** P0/P1/P2
- **Start Time:** 2024-01-15 14:30 UTC
- **End Time:** 2024-01-15 15:45 UTC
- **Duration:** 1h 15m
- **Impact:** [Description of user/business impact]
## Root Cause
[Detailed explanation of what went wrong and why]
## Timeline
| Time | Event |
|------|-------|
| 14:30 | Issue detected via monitoring alert |
| 14:35 | Incident team assembled |
| 14:45 | Root cause identified |
| 15:00 | Fix developed and tested |
| 15:20 | Fix deployed to production |
| 15:45 | Issue confirmed resolved |
## Resolution
[What was done to fix the issue]
## Lessons Learned
### What went well
- Quick detection through monitoring
- Effective team coordination
- Minimal user impact
### What could be improved
- Earlier detection possible with better alerting
- Testing could have caught this issue
- Communication could be more proactive
## Action Items
- [ ] Improve monitoring for [specific area]
- [ ] Add automated test for [specific scenario]
- [ ] Update documentation for [specific process]
- [ ] Training on [specific topic] for team
## Prevention Measures
[How we'll prevent this from happening again]
```
### Post-Incident Review Process
1. **Schedule Review** (within 24-48 hours)
- Involve all key participants
- Book 60-90 minute session
- Prepare incident timeline
2. **Blameless Analysis**
- Focus on systems and processes, not individuals
- Understand contributing factors
- Identify improvement opportunities
3. **Action Plan**
- Concrete, assignable tasks
- Realistic timelines
- Clear success criteria
4. **Follow-up**
- Track action item completion
- Share learnings with broader team
- Update procedures based on insights
### Knowledge Sharing
#### Runbook Updates
After each hotfix, update relevant runbooks:
- Add new troubleshooting steps
- Update contact information
- Refine escalation procedures
- Document new tools or processes
#### Team Training
- Share incident learnings in team meetings
- Conduct tabletop exercises for common scenarios
- Update onboarding materials with hotfix procedures
- Create decision trees for severity classification
#### Automation Improvements
- Add alerts for new failure modes
- Automate manual steps where possible
- Improve deployment and rollback processes
- Enhance monitoring and observability
## Common Pitfalls and Best Practices
### Common Pitfalls
**Over-engineering the fix**
- Making broad changes instead of minimal targeted fix
- Adding features while fixing bugs
- Refactoring unrelated code
**Insufficient testing**
- Skipping automated tests due to time pressure
- Not testing the exact scenario that caused the issue
- Deploying without staging validation
**Poor communication**
- Not notifying stakeholders promptly
- Unclear or infrequent status updates
- Forgetting to announce resolution
**Inadequate monitoring**
- Not watching system health after deployment
- Missing secondary effects of the fix
- Failing to verify the issue is actually resolved
### Best Practices
**Keep fixes minimal and focused**
- Address only the specific issue
- Avoid scope creep or improvements
- Save refactoring for regular releases
**Maintain clear communication**
- Set up dedicated incident channel
- Provide regular status updates
- Use clear, non-technical language for business stakeholders
**Test thoroughly but efficiently**
- Focus testing on affected functionality
- Use automated tests where possible
- Validate in staging before production
**Document everything**
- Maintain timeline of events
- Record decisions and rationale
- Share lessons learned with team
**Plan for rollback**
- Always have a rollback plan ready
- Test rollback procedure in advance
- Monitor closely after deployment
By following these procedures and continuously improving based on experience, teams can handle production emergencies effectively while minimizing impact and learning from each incident.

View File

@@ -0,0 +1,410 @@
# Release Workflow Comparison
## Overview
This document compares the three most popular branching and release workflows: Git Flow, GitHub Flow, and Trunk-based Development. Each approach has distinct advantages and trade-offs depending on your team size, deployment frequency, and risk tolerance.
## Git Flow
### Structure
```
main (production)
release/1.2.0 ← develop (integration) ← feature/user-auth
↑ ← feature/payment-api
hotfix/critical-fix
```
### Branch Types
- **main**: Production-ready code, tagged releases
- **develop**: Integration branch for next release
- **feature/***: Individual features, merged to develop
- **release/X.Y.Z**: Release preparation, branched from develop
- **hotfix/***: Critical fixes, branched from main
### Typical Flow
1. Create feature branch from develop: `git checkout -b feature/login develop`
2. Work on feature, commit changes
3. Merge feature to develop when complete
4. When ready for release, create release branch: `git checkout -b release/1.2.0 develop`
5. Finalize release (version bump, changelog, bug fixes)
6. Merge release branch to both main and develop
7. Tag release: `git tag v1.2.0`
8. Deploy from main branch
### Advantages
- **Clear separation** between production and development code
- **Stable main branch** always represents production state
- **Parallel development** of features without interference
- **Structured release process** with dedicated release branches
- **Hotfix support** without disrupting development work
- **Good for scheduled releases** and traditional release cycles
### Disadvantages
- **Complex workflow** with many branch types
- **Merge overhead** from multiple integration points
- **Delayed feedback** from long-lived feature branches
- **Integration conflicts** when merging large features
- **Slower deployment** due to process overhead
- **Not ideal for continuous deployment**
### Best For
- Large teams (10+ developers)
- Products with scheduled release cycles
- Enterprise software with formal testing phases
- Projects requiring stable release branches
- Teams comfortable with complex Git workflows
### Example Commands
```bash
# Start new feature
git checkout develop
git checkout -b feature/user-authentication
# Finish feature
git checkout develop
git merge --no-ff feature/user-authentication
git branch -d feature/user-authentication
# Start release
git checkout develop
git checkout -b release/1.2.0
# Version bump and changelog updates
git commit -am "Bump version to 1.2.0"
# Finish release
git checkout main
git merge --no-ff release/1.2.0
git tag -a v1.2.0 -m "Release version 1.2.0"
git checkout develop
git merge --no-ff release/1.2.0
git branch -d release/1.2.0
# Hotfix
git checkout main
git checkout -b hotfix/security-patch
# Fix the issue
git commit -am "Fix security vulnerability"
git checkout main
git merge --no-ff hotfix/security-patch
git tag -a v1.2.1 -m "Hotfix version 1.2.1"
git checkout develop
git merge --no-ff hotfix/security-patch
```
## GitHub Flow
### Structure
```
main ← feature/user-auth
← feature/payment-api
← hotfix/critical-fix
```
### Branch Types
- **main**: Production-ready code, deployed automatically
- **feature/***: All changes, regardless of size or type
### Typical Flow
1. Create feature branch from main: `git checkout -b feature/login main`
2. Work on feature with regular commits and pushes
3. Open pull request when ready for feedback
4. Deploy feature branch to staging for testing
5. Merge to main when approved and tested
6. Deploy main to production automatically
7. Delete feature branch
### Advantages
- **Simple workflow** with only two branch types
- **Fast deployment** with minimal process overhead
- **Continuous integration** with frequent merges to main
- **Early feedback** through pull request reviews
- **Deploy from branches** allows testing before merge
- **Good for continuous deployment**
### Disadvantages
- **Main can be unstable** if testing is insufficient
- **No release branches** for coordinating multiple features
- **Limited hotfix process** requires careful coordination
- **Requires strong testing** and CI/CD infrastructure
- **Not suitable for scheduled releases**
- **Can be chaotic** with many simultaneous features
### Best For
- Small to medium teams (2-10 developers)
- Web applications with continuous deployment
- Products with rapid iteration cycles
- Teams with strong testing and CI/CD practices
- Projects where main is always deployable
### Example Commands
```bash
# Start new feature
git checkout main
git pull origin main
git checkout -b feature/user-authentication
# Regular work
git add .
git commit -m "feat(auth): add login form validation"
git push origin feature/user-authentication
# Deploy branch for testing
# (Usually done through CI/CD)
./deploy.sh feature/user-authentication staging
# Merge when ready
git checkout main
git merge feature/user-authentication
git push origin main
git branch -d feature/user-authentication
# Automatic deployment to production
# (Triggered by push to main)
```
## Trunk-based Development
### Structure
```
main ← short-feature-branch (1-3 days max)
← another-short-branch
← direct-commits
```
### Branch Types
- **main**: The single source of truth, always deployable
- **Short-lived branches**: Optional, for changes taking >1 day
### Typical Flow
1. Commit directly to main for small changes
2. Create short-lived branch for larger changes (max 2-3 days)
3. Merge to main frequently (multiple times per day)
4. Use feature flags to hide incomplete features
5. Deploy main to production multiple times per day
6. Release by enabling feature flags, not code deployment
### Advantages
- **Simplest workflow** with minimal branching
- **Fastest integration** with continuous merges
- **Reduced merge conflicts** from short-lived branches
- **Always deployable main** through feature flags
- **Fastest feedback loop** with immediate integration
- **Excellent for CI/CD** and DevOps practices
### Disadvantages
- **Requires discipline** to keep main stable
- **Needs feature flags** for incomplete features
- **Limited code review** for direct commits
- **Can be destabilizing** without proper testing
- **Requires advanced CI/CD** infrastructure
- **Not suitable for teams** uncomfortable with frequent changes
### Best For
- Expert teams with strong DevOps culture
- Products requiring very fast iteration
- Microservices architectures
- Teams practicing continuous deployment
- Organizations with mature testing practices
### Example Commands
```bash
# Small change - direct to main
git checkout main
git pull origin main
# Make changes
git add .
git commit -m "fix(ui): resolve button alignment issue"
git push origin main
# Larger change - short branch
git checkout main
git pull origin main
git checkout -b payment-integration
# Work for 1-2 days maximum
git add .
git commit -m "feat(payment): add Stripe integration"
git push origin payment-integration
# Immediate merge
git checkout main
git merge payment-integration
git push origin main
git branch -d payment-integration
# Feature flag usage
if (featureFlags.enabled('stripe_payments', userId)) {
return renderStripePayment();
} else {
return renderLegacyPayment();
}
```
## Feature Comparison Matrix
| Aspect | Git Flow | GitHub Flow | Trunk-based |
|--------|----------|-------------|-------------|
| **Complexity** | High | Medium | Low |
| **Learning Curve** | Steep | Moderate | Gentle |
| **Deployment Frequency** | Weekly/Monthly | Daily | Multiple/day |
| **Branch Lifetime** | Weeks/Months | Days/Weeks | Hours/Days |
| **Main Stability** | Very High | High | High* |
| **Release Coordination** | Excellent | Limited | Feature Flags |
| **Hotfix Support** | Built-in | Manual | Direct |
| **Merge Conflicts** | High | Medium | Low |
| **Team Size** | 10+ | 3-10 | Any |
| **CI/CD Requirements** | Medium | High | Very High |
*With proper feature flags and testing
## Release Strategies by Workflow
### Git Flow Releases
```bash
# Scheduled release every 2 weeks
git checkout develop
git checkout -b release/2.3.0
# Version management
echo "2.3.0" > VERSION
npm version 2.3.0 --no-git-tag-version
python setup.py --version 2.3.0
# Changelog generation
git log --oneline release/2.2.0..HEAD --pretty=format:"%s" > CHANGELOG_DRAFT.md
# Testing and bug fixes in release branch
git commit -am "fix: resolve issue found in release testing"
# Finalize release
git checkout main
git merge --no-ff release/2.3.0
git tag -a v2.3.0 -m "Release 2.3.0"
# Deploy tagged version
docker build -t app:2.3.0 .
kubectl set image deployment/app app=app:2.3.0
```
### GitHub Flow Releases
```bash
# Deploy every merge to main
git checkout main
git merge feature/new-payment-method
# Automatic deployment via CI/CD
# .github/workflows/deploy.yml triggers on push to main
# Tag releases for tracking (optional)
git tag -a v2.3.$(date +%Y%m%d%H%M) -m "Production deployment"
# Rollback if needed
git revert HEAD
git push origin main # Triggers automatic rollback deployment
```
### Trunk-based Releases
```bash
# Continuous deployment with feature flags
git checkout main
git add feature_flags.json
git commit -m "feat: enable new payment method for 10% of users"
git push origin main
# Gradual rollout
curl -X POST api/feature-flags/payment-v2/rollout/25 # 25% of users
# Monitor metrics...
curl -X POST api/feature-flags/payment-v2/rollout/50 # 50% of users
# Monitor metrics...
curl -X POST api/feature-flags/payment-v2/rollout/100 # Full rollout
# Remove flag after successful rollout
git rm old_payment_code.js
git commit -m "cleanup: remove legacy payment code"
```
## Choosing the Right Workflow
### Decision Matrix
**Choose Git Flow if:**
- ✅ Team size > 10 developers
- ✅ Scheduled release cycles (weekly/monthly)
- ✅ Multiple versions supported simultaneously
- ✅ Formal testing and QA processes
- ✅ Complex enterprise software
- ❌ Need rapid deployment
- ❌ Small team or startup
**Choose GitHub Flow if:**
- ✅ Team size 3-10 developers
- ✅ Web applications or APIs
- ✅ Strong CI/CD and testing
- ✅ Daily or continuous deployment
- ✅ Simple release requirements
- ❌ Complex release coordination needed
- ❌ Multiple release branches required
**Choose Trunk-based Development if:**
- ✅ Expert development team
- ✅ Mature DevOps practices
- ✅ Microservices architecture
- ✅ Feature flag infrastructure
- ✅ Multiple deployments per day
- ✅ Strong automated testing
- ❌ Junior developers
- ❌ Complex integration requirements
### Migration Strategies
#### From Git Flow to GitHub Flow
1. **Simplify branching**: Eliminate develop branch, work directly with main
2. **Increase deployment frequency**: Move from scheduled to continuous releases
3. **Strengthen testing**: Improve automated test coverage and CI/CD
4. **Reduce branch lifetime**: Limit feature branches to 1-2 weeks maximum
5. **Train team**: Educate on simpler workflow and increased responsibility
#### From GitHub Flow to Trunk-based
1. **Implement feature flags**: Add feature toggle infrastructure
2. **Improve CI/CD**: Ensure all tests run in <10 minutes
3. **Increase commit frequency**: Encourage multiple commits per day
4. **Reduce branch usage**: Start committing small changes directly to main
5. **Monitor stability**: Ensure main remains deployable at all times
#### From Trunk-based to Git Flow
1. **Add structure**: Introduce develop and release branches
2. **Reduce deployment frequency**: Move to scheduled release cycles
3. **Extend branch lifetime**: Allow longer feature development cycles
4. **Formalize process**: Add approval gates and testing phases
5. **Coordinate releases**: Plan features for specific release versions
## Anti-patterns to Avoid
### Git Flow Anti-patterns
- **Long-lived feature branches** (>2 weeks)
- **Skipping release branches** for small releases
- **Direct commits to main** bypassing develop
- **Forgetting to merge back** to develop after hotfixes
- **Complex merge conflicts** from delayed integration
### GitHub Flow Anti-patterns
- **Unstable main branch** due to insufficient testing
- **Long-lived feature branches** defeating the purpose
- **Skipping pull request reviews** for speed
- **Direct production deployment** without staging validation
- **No rollback plan** when deployments fail
### Trunk-based Anti-patterns
- **Committing broken code** to main branch
- **Feature branches lasting weeks** defeating the philosophy
- **No feature flags** for incomplete features
- **Insufficient automated testing** leading to instability
- **Poor CI/CD pipeline** causing deployment delays
## Conclusion
The choice of release workflow significantly impacts your team's productivity, code quality, and deployment reliability. Consider your team size, technical maturity, deployment requirements, and organizational culture when making this decision.
**Start conservative** (Git Flow) and evolve toward more agile approaches (GitHub Flow, Trunk-based) as your team's skills and infrastructure mature. The key is consistency within your team and alignment with your organization's goals and constraints.
Remember: **The best workflow is the one your team can execute consistently and reliably**.