Git Best Practices
This chapter introduces Git best practices, including commit conventions, branch strategies, team collaboration, and project management suggestions, helping you and your team use Git more efficiently.
Commit Best Practices
Commit Message Conventions
Semantic Commit Messages
Use the Conventional Commits format:
<type>[optional scope]: <description>
[optional body]
[optional footer(s)]Commit Types
bash
feat: # New feature
fix: # Bug fix
docs: # Documentation update
style: # Code formatting (no logic change)
refactor: # Refactoring (neither new feature nor bug fix)
test: # Adding or modifying tests
chore: # Build process or auxiliary tool changes
perf: # Performance optimization
ci: # CI/CD related
build: # Build system or external dependency changes
revert: # Reverting previous commitExamples of Good Commit Messages
bash
# ✅ Good commit messages
git commit -m "feat(auth): Add OAuth 2.0 login support"
git commit -m "fix(ui): Fix mobile navigation menu display issue"
git commit -m "docs: Update API documentation and usage examples"
git commit -m "refactor(utils): Refactor date processing function to improve performance"
# Commit with detailed description
git commit -m "feat(payment): Integrate Stripe payment gateway
- Add payment form component
- Implement payment status tracking
- Add payment failure retry mechanism
- Update related test cases
Closes #123"Commit Messages to Avoid
bash
# ❌ Avoid these commit messages
git commit -m "Modify"
git commit -m "Update code"
git commit -m "Temporary commit"
git commit -m "fix bug"
git commit -m "WIP" # Work In Progress
git commit -m "asdf"Commit Granularity
Atomic Commits
Each commit should be a logically complete change:
bash
# ✅ Good practice: One feature per commit
git add user_model.py
git commit -m "feat(models): Add user model"
git add user_controller.py
git commit -m "feat(api): Add user API endpoints"
git add user_tests.py
git commit -m "test(user): Add user model and API tests"
# ❌ Avoid: Multiple unrelated changes in one commit
git add user_model.py login_form.js payment_service.py
git commit -m "Add user feature and payment feature"Using Staging Area for Precise Control
bash
# Partially add file changes
git add -p filename.py
# Interactive add
git add -i
# Add specific patch
git add --patchCommit Frequency
bash
# ✅ Good commit frequency
# - Commit after completing a small feature
# - Commit after fixing a bug
# - Commit after refactoring a function
# - Commit at least once a day
# ❌ Avoid these frequencies
# - Commit massive changes only once a week
# - Commit tiny changes every minute
# - Commit incomplete featuresBranch Management Best Practices
Branch Naming Conventions
bash
# Feature branches
feature/user-authentication
feature/payment-integration
feature/issue-123-user-profile
# Fix branches
bugfix/login-validation-error
bugfix/memory-leak-fix
hotfix/security-vulnerability
# Release branches
release/v1.2.0
release/2023-q4
# Experiment branches
experiment/new-ui-framework
experiment/performance-optimization
# Personal branches
username/feature-name
john/user-dashboardBranch Lifecycle Management
bash
# Create feature branch
git checkout -b feature/user-profile main
# Regularly sync with main branch
git checkout main
git pull origin main
git checkout feature/user-profile
git rebase main # or git merge main
# Merge after feature completion
git checkout main
git merge --no-ff feature/user-profile
# Delete merged branch
git branch -d feature/user-profile
git push origin --delete feature/user-profileBranch Protection Strategy
bash
# Protection rules for main branch:
# 1. Prohibit direct push to main/master
# 2. Require Pull Request reviews
# 3. Require status checks to pass
# 4. Require branches to be up to date
# 5. Restrict who can push to protected branchesCode Review Best Practices
Pull Request Conventions
PR Title and Description
markdown
# PR Title Format
feat(auth): Add OAuth 2.0 login support
# PR Description Template
## Changes
- Added OAuth 2.0 login flow
- Implemented user info fetching and storage
- Added login status management
## Testing
- [ ] Unit tests passed
- [ ] Integration tests passed
- [ ] Manual testing completed
## Screenshots/Demo
(If UI changes, add screenshots or GIF)
## Related Issues
Closes #123
Related to #456
## Checklist
- [ ] Code follows project standards
- [ ] Added necessary tests
- [ ] Updated related documentation
- [ ] No breaking changesCode Review Checkpoints
bash
# Functional Check
- Does the code implement expected functionality?
- Are edge cases handled?
- Is error handling complete?
# Code Quality Check
- Is the code readable and understandable?
- Does it follow project coding standards?
- Is there duplicated code?
- Are variable and function names reasonable?
# Performance Check
- Are there performance issues?
- Are database queries optimized?
- Is there risk of memory leaks?
# Security Check
- Are there security vulnerabilities?
- Is input validation sufficient?
- Are sensitive info handled correctly?
# Testing Check
- Is test coverage sufficient?
- Are test cases reasonable?
- Are there integration tests?Review Tool Configuration
bash
# Set PR template
mkdir -p .github/pull_request_template
cat > .github/pull_request_template/default.md << 'EOF'
## Change Type
- [ ] New feature
- [ ] Bug fix
- [ ] Documentation update
- [ ] Refactoring
- [ ] Performance optimization
- [ ] Other
## Description
## Testing
- [ ] Added new tests
- [ ] All tests passed
- [ ] Manual testing completed
## Checklist
- [ ] Code follows project standards
- [ ] Self-review completed
- [ ] Related documentation updated
EOFTeam Collaboration Best Practices
Workflow Selection
GitHub Flow (Small Teams)
bash
# 1. Create feature branch from main
git checkout -b feature/new-feature main
# 2. Develop and commit
git add .
git commit -m "feat: Implement new feature"
# 3. Push branch
git push -u origin feature/new-feature
# 4. Create Pull Request
# 5. Code Review
# 6. Merge to main
# 7. Delete feature branchGit Flow (Large Teams)
bash
# Main branches
main/master # Production branch
develop # Development branch
# Supporting branches
feature/* # Feature branches
release/* # Release branches
hotfix/* # Hotfix branchesConflict Resolution Strategy
bash
# Prevent conflicts
# 1. Sync main branch frequently
git checkout feature-branch
git rebase main
# 2. Keep feature branches small and focused
# 3. Merge completed features timely
# Resolve conflicts
# 1. Pull latest code
git pull origin main
# 2. Merge or rebase
git merge main # or git rebase main
# 3. Resolve conflict files
# Edit conflicted files, remove conflict markers
# 4. Mark conflict as resolved
git add conflicted_file.py
git commit # or git rebase --continueTeam Communication
bash
# Reference Issue in commit message
git commit -m "fix(auth): Fix login timeout issue
Fixed issue where session timed out after user login, now refreshes token correctly.
Fixes #123"
# Mention people in PR
# @reviewer Please help review this PR
# @designer Please confirm if UI implementation matches design
# @qa This feature is ready for testingProject Management Best Practices
Version Management
Semantic Versioning
bash
# Version format: MAJOR.MINOR.PATCH
# 1.0.0 -> 1.0.1 (Patch version)
# 1.0.1 -> 1.1.0 (Minor version)
# 1.1.0 -> 2.0.0 (Major version)
# Create version tag
git tag -a v1.2.0 -m "Release version 1.2.0"
git push origin v1.2.0
# Pre-release version
git tag -a v1.2.0-beta.1 -m "Beta release 1.2.0-beta.1"Changelog
markdown
# CHANGELOG.md
## [1.2.0] - 2023-12-01
### Added
- Added user authentication feature
- Added payment integration
### Changed
- Optimized database query performance
- Updated UI design
### Fixed
- Fixed login page style issue
- Resolved memory leak issue
### Removed
- Removed deprecated API endpointsDocumentation Management
bash
# Project documentation structure
README.md # Project overview and quick start
CONTRIBUTING.md # Contribution guidelines
CODE_OF_CONDUCT.md # Code of conduct
CHANGELOG.md # Change log
LICENSE # License
docs/ # Detailed documentation
├── api.md # API documentation
├── setup.md # Setup guide
└── deployment.md # Deployment guideREADME Template
markdown
# Project Name
Short project description
## Features
- Feature 1
- Feature 2
- Feature 3
## Quick Start
### Requirements
- Node.js >= 14
- Python >= 3.8
- Docker
### Installation
```bash
git clone https://github.com/user/project.git
cd project
npm installRun
bash
npm startDocumentation
Contributing
Please read CONTRIBUTING.md to understand how to contribute code.
License
This project is licensed under the MIT License - see the LICENSE file for details.
### Automation Tools
#### Git Hooks Automation
```bash
# pre-commit hook
#!/bin/bash
# Code format check
npm run lint
if [ $? -ne 0 ]; then
echo "Code format check failed, please fix before committing"
exit 1
fi
# Run tests
npm test
if [ $? -ne 0 ]; then
echo "Tests failed, please fix before committing"
exit 1
fiCI/CD Configuration
yaml
# .github/workflows/ci.yml
name: CI
on:
push:
branches: [ main, develop ]
pull_request:
branches: [ main ]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Setup Node.js
uses: actions/setup-node@v2
with:
node-version: '16'
- name: Install dependencies
run: npm ci
- name: Run linter
run: npm run lint
- name: Run tests
run: npm test
- name: Build
run: npm run buildSecurity Best Practices
Sensitive Information Management
bash
# Use .gitignore to exclude sensitive files
echo "*.env" >> .gitignore
echo "config/secrets.json" >> .gitignore
echo "*.key" >> .gitignore
echo "*.pem" >> .gitignore
# Use environment variables
# Don't do this:
git add config.py # Contains API_KEY = "secret123"
# Do this:
# config.py: API_KEY = os.getenv('API_KEY')
# .env: API_KEY=secret123Commit Signing
bash
# Configure GPG signing
git config --global user.signingkey YOUR_GPG_KEY_ID
git config --global commit.gpgsign true
# Sign commit
git commit -S -m "feat: Add new feature"
# Verify signature
git log --show-signatureAccess Control
bash
# Repository access control suggestions:
# 1. Use SSH keys instead of passwords
# 2. Regularly rotate access tokens
# 3. Use different deployment keys for different environments
# 4. Enable two-factor authentication
# 5. Regularly review repository access permissionsPerformance Optimization Best Practices
Repository Size Management
bash
# Avoid committing large files
# Use Git LFS for large files
git lfs track "*.psd"
git lfs track "*.zip"
git add .gitattributes
# Clean large files from history
git filter-repo --strip-blobs-bigger-than 10M
# Regular garbage collection
git gc --aggressive --prune=nowClone Optimization
bash
# Shallow clone
git clone --depth 1 https://github.com/user/repo.git
# Partial clone
git clone --filter=blob:none https://github.com/user/repo.git
# Single branch clone
git clone --single-branch --branch main https://github.com/user/repo.gitMonitoring and Analysis
Repository Health Check
bash
#!/bin/bash
# Repository health check script
echo "=== Git Repository Health Check ==="
# Check repository size
echo "Repository size: $(du -sh .git | cut -f1)"
# Check object count
echo "Object count: $(git count-objects -v | grep 'count' | cut -d' ' -f2)"
# Check largest files
echo "Largest files:"
git rev-list --objects --all | git cat-file --batch-check='%(objecttype) %(objectname) %(objectsize) %(rest)' | sed -n 's/^blob //p' | sort -k2nr | head -5
# Check active branches
echo "Active branches: $(git branch -r | wc -l)"
# Check commit activity in last 30 days
echo "Commits in last 30 days: $(git log --since='30 days ago' --oneline | wc -l)"
# Check contributors
echo "Contributor count: $(git shortlog -sn | wc -l)"Commit Statistics
bash
#!/bin/bash
# Commit statistics script
echo "=== Commit Statistics Analysis ==="
# Stats by author
echo "Commits by author:"
git shortlog -sn | head -10
# Stats by month
echo "Commits by month:"
git log --date=format:'%Y-%m' --pretty=format:'%ad' | sort | uniq -c
# Stats by file type
echo "Changes by file type:"
git log --name-only --pretty=format: | grep -E '\.(js|py|java|go)$' | sort | uniq -c | sort -rn
# Lines of code stats
echo "Lines of code changes:"
git log --shortstat --since='1 month ago' | grep -E "fil(e|es) changed" | awk '{files+=$1; inserted+=$4; deleted+=$6} END {print "Files changed:", files, "Lines inserted:", inserted, "Lines deleted:", deleted}'Troubleshooting Best Practices
Common Issue Prevention
bash
# 1. Regularly backup important branches
git bundle create backup.bundle main develop
# 2. Use reflog to recover lost commits
git reflog expire --expire=90.days.ago --all
# 3. Set auto cleanup
git config --global gc.auto 256
# 4. Enable rerere (reuse recorded resolution)
git config --global rerere.enabled trueEmergency Response Process
bash
# Emergency rollback process
# 1. Create backup branch
git branch emergency-backup
# 2. Rollback to safe version
git reset --hard last_known_good_commit
# 3. Force push (requires team agreement)
git push --force-with-lease origin main
# 4. Notify team
# 5. Analyze root cause
# 6. Formulate fix planSummary
Key points of Git Best Practices:
Commit Conventions
- ✅ Use semantic commit messages
- ✅ Maintain commit atomicity
- ✅ Frequent small commits
- ✅ Detailed description for important changes
Branch Management
- ✅ Use clear branch naming
- ✅ Keep branch lifecycle short
- ✅ Regularly sync with main branch
- ✅ Clean up merged branches timely
Team Collaboration
- ✅ Establish code review process
- ✅ Use Pull Request workflow
- ✅ Maintain good communication
- ✅ Unify workflow and standards
Project Management
- ✅ Maintain clear documentation
- ✅ Use semantic versioning
- ✅ Automate testing and deployment
- ✅ Regularly monitor repository health
Security and Performance
- ✅ Protect sensitive information
- ✅ Use signed commits
- ✅ Control repository size
- ✅ Optimize clone and operation performance
By following these best practices, you and your team can:
- 📈 Improve development efficiency and code quality
- 🤝 Improve team collaboration and communication
- 🛡️ Enhance project security and stability
- 🚀 Establish scalable development processes
In the next chapter, we will learn about Git and GitHub operations.