Git - Best Practices
Advanced
Following Git best practices ensures maintainable, secure, and collaborative development. These proven patterns help teams scale while maintaining code quality and project history.
Commit Best Practices
Commit Message Conventions
Conventional Commits format:
type(scope): subject line (max 50 characters)
Optional body paragraph explaining the what, why, and how.
Keep lines under 72 characters for proper formatting in
various Git tools and interfaces.
Optional footer for breaking changes, issue references:
Fixes #123
BREAKING CHANGE: API endpoint /users now requires auth
Commit Types
Type | Purpose | Example |
---|---|---|
feat | New feature | feat(auth): add OAuth2 login |
fix | Bug fix | fix(api): handle null user response |
docs | Documentation | docs(readme): update installation steps |
style | Code style | style: fix linting errors |
refactor | Code restructure | refactor(db): optimize user queries |
test | Add/modify tests | test(auth): add login edge cases |
chore | Maintenance | chore: update dependencies |
perf | Performance | perf(api): cache user sessions |
ci | CI/CD changes | ci: add automated testing |
revert | Revert changes | revert: "feat(auth): add OAuth2" |
Good vs Bad Commits
❌ Bad commit examples:
git commit -m "fix"
git commit -m "WIP"
git commit -m "oops"
git commit -m "trying to fix the thing that broke"
git commit -m "Final version (really this time)"
✅ Good commit examples:
git commit -m "fix(auth): resolve session timeout issue
Users were being logged out unexpectedly due to incorrect
session expiry calculation. Updated the timestamp logic
to use UTC and increased default timeout to 24 hours.
Fixes #456"
Branching Strategies
Branch Naming Conventions
Recommended patterns:
# Feature branches
feature/user-authentication
feature/JIRA-123-payment-gateway
feature/user/john/shopping-cart
# Bug fixes
bugfix/login-error
hotfix/security-patch-cve-2023-001
fix/issue-456-memory-leak
# Release branches
release/v2.1.0
release/2023-Q4
# Maintenance
chore/update-dependencies
docs/api-documentation
refactor/user-service
Choosing the Right Workflow
Team Size | Release Frequency | Recommended Workflow |
---|---|---|
1-3 developers | Continuous | GitHub Flow |
4-10 developers | Weekly/Monthly | Feature Branch + PR |
10+ developers | Scheduled | GitFlow |
Open Source | Varies | Forking Workflow |
Branch Lifecycle Management
Branch cleanup workflow:
# After feature completion
git switch main
git pull origin main
git branch -d feature/user-auth # Delete local branch
git push origin --delete feature/user-auth # Delete remote
# Automated cleanup script
git for-each-ref --format='%(refname:short) %(committerdate)' refs/heads \
| awk '$2 <= "'$(date -d '30 days ago' +%Y-%m-%d)'"' \
| cut -d' ' -f1 \
| xargs -r git branch -D
Code Review Best Practices
Pull Request Guidelines
PR template example:
## Description
Brief description of changes and motivation.
## Type of Change
- [ ] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected)
- [ ] Documentation update
## Testing
- [ ] Unit tests pass
- [ ] Integration tests pass
- [ ] Manual testing completed
- [ ] Performance impact assessed
## Checklist
- [ ] Code follows style guidelines
- [ ] Self-review completed
- [ ] Comments added for complex logic
- [ ] Documentation updated
- [ ] No sensitive data exposed
## Screenshots (if applicable)
[Include screenshots for UI changes]
## Related Issues
Fixes #123
Related to #456
Review Process
Reviewer responsibilities:
Code Quality:
✅ Logic correctness and edge cases
✅ Performance implications
✅ Security vulnerabilities
✅ Code maintainability
Style and Standards:
✅ Consistent formatting
✅ Naming conventions
✅ Documentation completeness
✅ Test coverage
Architecture:
✅ Design patterns usage
✅ Dependency management
✅ API consistency
✅ Database schema changes
Security Best Practices
Sensitive Data Protection
Never commit these:
# API keys and secrets
API_KEY=abc123
SECRET_TOKEN=xyz789
# Database credentials
DATABASE_PASSWORD=secret123
# Private keys
-----BEGIN RSA PRIVATE KEY-----
# Configuration with secrets
config.production.json (with passwords)
# IDE and system files
.DS_Store
.vscode/settings.json (with personal tokens)
Security Measures
# Use environment variables
DATABASE_URL=${DATABASE_URL}
API_KEY=${API_KEY}
# Create proper .gitignore
echo ".env" >> .gitignore
echo "*.log" >> .gitignore
echo "config/secrets.yml" >> .gitignore
# Use Git secrets detection
git secrets --register-aws
git secrets --install
git secrets --scan
Commit Signing
# Setup GPG signing
git config --global user.signingkey YOUR_GPG_KEY
git config --global commit.gpgsign true
git config --global tag.gpgsign true
# Setup SSH signing (Git 2.34+)
git config --global gpg.format ssh
git config --global user.signingkey ~/.ssh/id_ed25519.pub
git config --global commit.gpgsign true
Repository Organization
Directory Structure
Standard project layout:
project-root/
├── README.md # Project overview and setup
├── CONTRIBUTING.md # Contribution guidelines
├── LICENSE # Software license
├── .gitignore # Git ignore rules
├── .gitattributes # Git attributes
├── package.json # Dependencies and scripts
├── docker-compose.yml # Development environment
├── docs/ # Project documentation
│ ├── api/ # API documentation
│ └── deployment/ # Deployment guides
├── src/ # Source code
│ ├── components/ # Reusable components
│ ├── services/ # Business logic
│ └── utils/ # Helper functions
├── tests/ # Test files
│ ├── unit/ # Unit tests
│ ├── integration/ # Integration tests
│ └── e2e/ # End-to-end tests
├── scripts/ # Build and deployment scripts
└── config/ # Configuration files
├── development.yml
├── staging.yml
└── production.example.yml
Essential Repository Files
README.md template:
# Project Name
Brief description of what the project does.
## Features
- Feature 1
- Feature 2
- Feature 3
## Installation
```bash
git clone https://github.com/username/project.git
cd project
npm install
```
## Usage
```bash
npm start
```
## Development
```bash
npm run dev
```
## Testing
```bash
npm test
```
## Contributing
Please read [CONTRIBUTING.md](CONTRIBUTING.md) for details.
## License
This project is licensed under the MIT License - see [LICENSE](LICENSE) file.
Development Workflow
Daily Development Routine
Morning startup:
# 1. Update main branch
git switch main
git pull origin main
# 2. Check for updates in current feature
git switch feature/current-work
git rebase main # or git merge main
# 3. Check repository status
git status
git log --oneline -5
Feature Development Cycle
Complete feature workflow:
# 1. Start feature
git switch main
git pull origin main
git switch -c feature/new-feature
# 2. Development with regular commits
git add .
git commit -m "feat(module): add initial structure"
# ... more work ...
git commit -m "feat(module): implement core logic"
# ... more work ...
git commit -m "test(module): add unit tests"
# 3. Pre-merge preparation
git switch main
git pull origin main
git switch feature/new-feature
git rebase main # Resolve conflicts if needed
# 4. Push and create PR
git push -u origin feature/new-feature
# Create PR via GitHub/GitLab UI
# 5. After PR approval and merge
git switch main
git pull origin main
git branch -d feature/new-feature
Performance and Scalability
Repository Optimization
# Regular maintenance
git gc --aggressive --prune=now
git repack -Ad
git prune-packed
# Check repository size
git count-objects -vH
# Find large files
git rev-list --objects --all | grep -E "\.zip|\.tar|\.gz|\.bin"
# Use Git LFS for large files
git lfs track "*.zip"
git lfs track "*.bin"
git add .gitattributes
Large Repository Strategies
# Shallow clone for CI/CD
git clone --depth 1 https://github.com/user/repo.git
# Partial clone (Git 2.19+)
git clone --filter=blob:none https://github.com/user/repo.git
# Sparse checkout for large monorepos
git clone --filter=blob:none https://github.com/user/monorepo.git
cd monorepo
git sparse-checkout init --cone
git sparse-checkout set src/my-service docs/
Team Collaboration
Communication Guidelines
Git message etiquette:
Commit Messages:
✅ Use imperative mood ("Add feature" not "Added feature")
✅ Keep subject line under 50 characters
✅ Explain WHY, not just WHAT
✅ Reference issues and tickets
PR Descriptions:
✅ Explain the problem being solved
✅ Describe the solution approach
✅ Include testing information
✅ Add screenshots for UI changes
Code Reviews:
✅ Be constructive and respectful
✅ Focus on the code, not the person
✅ Explain the reasoning behind suggestions
✅ Acknowledge good code when you see it
Conflict Resolution
Merge conflict prevention:
# Keep feature branches short-lived
# Regularly sync with main branch
git fetch origin
git rebase origin/main
# Communicate about overlapping work
# Use feature flags for incomplete features
# Break large features into smaller chunks
Continuous Integration
CI/CD Best Practices
GitHub Actions example:
# .github/workflows/ci.yml
name: CI/CD Pipeline
on:
push:
branches: [ main, develop ]
pull_request:
branches: [ main ]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '18'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Run linting
run: npm run lint
- name: Run tests
run: npm run test:coverage
- name: Upload coverage
uses: codecov/codecov-action@v3
- name: Build application
run: npm run build
- name: Run security audit
run: npm audit
Documentation Standards
Code Documentation
Documentation hierarchy:
README.md # Project overview, quick start
CONTRIBUTING.md # How to contribute
CHANGELOG.md # Release notes and changes
docs/ # Detailed documentation
├── architecture/ # System design
├── api/ # API documentation
├── deployment/ # Deployment guides
└── troubleshooting/ # Common issues
# Inline code comments
/**
* Calculates the total price including tax
* @param {number} basePrice - The base price before tax
* @param {number} taxRate - Tax rate as decimal (0.1 for 10%)
* @returns {number} Total price including tax
* @throws {Error} When basePrice is negative
*/
function calculateTotal(basePrice, taxRate) {
if (basePrice < 0) {
throw new Error('Base price cannot be negative');
}
return basePrice * (1 + taxRate);
}
Monitoring and Analytics
Repository Health Metrics
# Track repository statistics
git log --format="%an" | sort | uniq -c | sort -rn # Contributors
git log --since="1 month ago" --format="%an" | wc -l # Recent activity
git log --oneline | wc -l # Total commits
git ls-files | wc -l # File count
# Branch health
git for-each-ref --format='%(refname:short) %(committerdate)' refs/heads | sort -k2
# PR metrics (using GitHub CLI)
gh pr list --state all --json number,createdAt,closedAt | jq length
Summary
You now understand Git best practices:
- ✅ Commit message conventions and atomic commits
- ✅ Branching strategies for different team sizes
- ✅ Code review processes and PR guidelines
- ✅ Security practices and sensitive data protection
- ✅ Repository organization and documentation
- ✅ Performance optimization for large repositories
- ✅ Team collaboration and communication
Next Steps
Now that you understand best practices, let's explore Git troubleshooting and problem resolution:
Practice Tip: Implement these practices gradually in your team. Start with commit conventions and basic branching, then add more sophisticated processes as the team matures.