Git Best Practices and Team Collaboration Guide
Good Git practices can significantly improve team collaboration and code quality. This section summarizes Git best practices, including commit guidelines, branching strategies, workflows, and team collaboration.
1. Submission Guidelines
(1) Why Is Standardized Commit Information Necessary?
Properly formatted submission information can:
- Clearly describe changes: Quickly understand what’s included in each commit
- Automation Tool Support: Automatically generate change logs
- Easy to trace history: Look up development records for specific features
- Improve collaboration efficiency: Reduce communication costs
(2) Conventional Commits Standard
This is the most popular commit message convention currently:
<type>(<scope>): <subject>
<body>
<footer>
Explanation of Each Section:
- type (required): Submission type
- scope (optional): Scope of impact
- subject (required): Brief description (50 characters or fewer)
- body (optional): Detailed description
- footer (optional): Footer information (e.g., "Close Issue")
(3) Detailed Explanation of Submission Types
| Type | Description | Example |
|---|---|---|
| feat | New Feature | feat: Added user login functionality |
| fix | Bug Fix | fix: Fixed login authentication error |
| docs | Documentation Updates | docs: Update API Documentation |
| style | Code formatting | style: Adjust code indentation |
| refactor | Refactoring | refactor: Optimize query logic |
| perf | Performance Optimization | perf: Optimizing Database Queries |
| test | Test | test: Add unit test |
| chore | Build/Tools | chore: Update build configuration |
| ci | CI Configuration | ci: Add GitHub Actions |
| revert | Revert | revert: Revert the login feature |
▶ Example: Proper commit message
# Single-line commit
git commit -m "feat: Add User Login Functionality"
# Range-Based Submissions
git commit -m "feat(auth): AddJWTCertification Support"
# Multi-line commit
git commit -m "feat(auth): AddOAuth2.0Login Support" -m "- SupportGoogle、GitHubLog In" -m "- Add Login State Persistence" -m "Closes #123"
# Use the editor to write a detailed commit message
git commit
(4) Best Practices for Submitting Information
Good commit messages:
feat(auth): AddOAuth2.0Login Support
- SupportGoogle、GitHub、WeChat Third-Party Login
- Add Login State Persistence
- Enable Auto-RefreshTokenMechanism
Closes #456
Poor commit messages:
update
fix bug
I made a few changes.
WIP
asdfasdf
Best Practices:
- ✅ Use an imperative sentence (Add instead of Added)
- ✅ Lowercase the first letter
- ✅ Do not add a period at the end
- ✅ Describe the topic in 50 characters or fewer
- ✅ The "Body" section explains the "What" and "Why," not the "How"
2. Branching Strategy
(1) The Git Flow Model
Git Flow is the most classic branching strategy:
graph TB
main[main<br/>Production Environment] --> release[release/*<br/>Preparing for Release]
release --> develop[develop<br/>Development Environment]
develop --> feature[feature/*<br/>Feature Development]
main --> hotfix[hotfix/*<br/>Emergency Fix]
style main fill:#d4edda
style develop fill:#fff3cd
style feature fill:#e1f5ff
style hotfix fill:#f8d7da
Branch Type:
- main: Production environment code; always kept in a deployable state
- develop: Develop code in the development environment and integrate various feature branches
- feature: Feature development branch, created from the "develop" branch
- release: A release-ready branch created from
develop - hotfix: Emergency fix branch, created from main
▶ Example: Git Flow Workflow
# 1. Create a feature branch from develop
git checkout develop
git checkout -b feature/user-auth
# 2. Develop and Submit
git add .
git commit -m "feat(auth): Add User Authentication"
# 3. Merge back intodevelop
git checkout develop
git merge --no-ff feature/user-auth
git branch -d feature/user-auth
# 4. Create a release branch
git checkout -b release/v1.0.0
# 5. Preparing for Release(FixBug、Update version numbers, etc.)
git commit -m "chore: Update the version number to1.0.0"
# 6. Merge into main and develop
git checkout main
git merge --no-ff release/v1.0.0
git tag -a v1.0.0 -m "Version 1.0.0"
git checkout develop
git merge --no-ff release/v1.0.0
git branch -d release/v1.0.0
# 7. Emergency Fix
git checkout main
git checkout -b hotfix/critical-bug
git commit -m "fix: Urgent FixBug"
git checkout main
git merge --no-ff hotfix/critical-bug
git tag -a v1.0.1 -m "Version 1.0.1"
git checkout develop
git merge --no-ff hotfix/critical-bug
git branch -d hotfix/critical-bug
(2) The GitHub Flow Model
GitHub Flow is simpler and better suited for continuous deployment:
graph LR
A[main<br/>Always deployable] --> B[featureBranch]
B --> C[Pull Request]
C --> D[Merge intomain]
D --> E[Automatic Deployment]
style A fill:#d4edda
style E fill:#c3e6cb
Features:
- The main branch is always deployable
- Create a feature branch from
main - Create a pull request once development is complete
- Merge into main after review
- Automatic deployment after merging
▶ Example: GitHub Flow Workflow
# 1. Update Locallymain
git checkout main
git pull origin main
# 2. Create a feature branch
git checkout -b feature/new-feature
# 3. Develop and Submit
git add .
git commit -m "feat: Add a New Feature"
# 4. Push Branch
git push -u origin feature/new-feature
# 5. Create a Pull Request on GitHub
# 6. Merge after the code review is approved
# 7. Clean Up Branches
git checkout main
git pull origin main
git branch -d feature/new-feature
git push origin --delete feature/new-feature
(3) Branch Naming Conventions
| Branch Type | Naming Convention | Example |
|---|---|---|
| Feature | feature/* | feature/user-authentication |
| Bugfix | fix/* | fix/login-validation |
| Hotfix | hotfix/* | hotfix/security-vulnerability |
| Release | release/* | release/v1.0.0 |
| Experiment | experiment/* | experiment/new-architecture |
3. Workflow
(1) Daily Development Workflow
sequenceDiagram
participant Developer
participant Local Warehouse
participant Remote Repository
participant CI/CD
Developer->>Local Warehouse: git pullUpdate the code
Developer->>Local Warehouse: Create a feature branch
Developer->>Local Warehouse: Develop and Submit
Developer->>Remote Repository: git pushPush Branch
Developer->>Remote Repository: CreatePull Request
Remote Repository->>CI/CD: Automated Testing
CI/CD->>Remote Repository: Test Passed
Remote Repository->>Local Warehouse: Merge intomain
Developer->>Local Warehouse: git pullSynchronize
(2) Feature Development Process
▶ Example: Complete Feature Development Process
# 1. Start Developing New Features
git checkout main
git pull origin main
git checkout -b feature/user-profile
# 2. Submit Regularly(Iterate quickly)
git add src/profile.js
git commit -m "feat(profile): Add User Profile Page"
git add src/api/profile.js
git commit -m "feat(profile): Add InformationAPIInterface"
git add src/test/profile.test.js
git commit -m "test(profile): Add Unit Tests"
# 3. Stay in touch withmainSynchronize
git fetch origin
git rebase origin/main
# 4. Push and CreatePR
git push -u origin feature/user-profile
# 5. PRMerge after approval
# 6. Cleanup
git checkout main
git pull origin main
git branch -d feature/user-profile
(3) Bug Fixing Process
▶ Example: Bug Fixing Process
# 1. Create a fix branch from main
git checkout main
git pull origin main
git checkout -b fix/login-error
# 2. Identify and FixBug
# View logs to troubleshoot issues
git log --grep="login"
# Fix the code
git add src/auth.js
git commit -m "fix(auth): Fix the login authentication error
- Fix the validation logic for empty passwords
- Add an input length check
Fixes #789"
# 3. Push and CreatePR
git push -u origin fix/login-error
# 4. Post-merger cleanup
git checkout main
git pull origin main
git branch -d fix/login-error
4. Teamwork Skills
(1) Code Review
Best Practices for Pull Requests:
When creating a PR:
- ✅ Write clear PR titles and descriptions
- ✅ Link to the relevant issue
- ✅ Keep PRs small and focused (<400 lines of code)
- ✅ Ensure that CI tests pass
- ✅ Add any necessary screenshots or demos
When reviewing a PR:
- ✅ Check code quality and logic
- ✅ Run local tests
- ✅ Offer constructive feedback
- ✅ Respond promptly to review comments
▶ Example: PR Description Template
Feature Description
Add User Profile Page,Supports viewing and editing user information。
Details of the Changes
- New Profile Components
- Add Information Edit Form
- Implement the profile picture upload feature
- Add Unit Tests
Test
- [x] Unit tests passed
- [x] Manual testing completed
- [x] Responsive Layout Testing
Screenshot
[Add a screenshot]
RelatedIssue
Closes #123
(2) Conflict Resolution Strategies
▶ Example: Preventing and Resolving Conflicts
# Conflict Prevention
# 1. Synchronize remote code frequently
git fetch origin
git rebase origin/main
# 2. Iterate quickly,Frequent Submissions
# Commit after completing each small feature
# 3. Timely Communication,Scope of Coordinated Revisions
# Resolving Conflicts
# 1. Pull the latest code
git pull --rebase origin main
# 2. Resolving Conflicts
# Editing Files with Conflicts,Keep the correct content
# 3. Mark the conflict as resolved
git add .
# 4. Continuerebase
git rebase --continue
# 5. Push
git push origin feature
(3) Keep the history organized
▶ Example: A Clean Commit History
# UsagerebaseMerge Commit
git rebase -i HEAD~3
# In the editor:
# pick a1b2c3d feat: Add FeatureA
# squash d4e5f6g feat: Improve functionalityA
# squash h7i8j9k feat: Optimization FeaturesA
# Edit the merged commit message after saving
# feat: Add FeatureA
# Usagerebaserather thanmerge
git pull --rebase origin main
# View the complete history
git log --oneline --graph
# Output:
# * a1b2c3d feat: Add FeatureC
# * d4e5f6g feat: Add FeatureB
# * h7i8j9k feat: Add FeatureA
5. Best Practices for Git Configuration
(1) Recommended Global Settings
▶ Example: Configuring Git
# User Information
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"
# Default Editor
git config --global core.editor "code --wait"
# Default branch name
git config --global init.defaultBranch main
# Automatic Line Break Conversion
git config --global core.autocrlf input # Linux/Mac
git config --global core.autocrlf true # Windows
# Pull Strategy
git config --global pull.rebase true
# Push Strategy
git config --global push.default simple
# Voucher Storage
git config --global credential.helper store
# Alias Configuration
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.lg "log --oneline --graph --all"
(2) .gitignore Configuration
▶ Example: A complete .gitignore file
# Dependency Directory
node_modules/
vendor/
venv/
# Compilation Output
dist/
build/
out/
*.o
*.class
*.jar
*.exe
# IDELayout
.vscode/
.idea/
*.swp
*.swo
.DS_Store
# Environment Configuration
.env
.env.local
.env.*.local
config.local.js
# Log Files
*.log
logs/
npm-debug.log*
yarn-debug.log*
# Test Coverage
coverage/
.nyc_output/
# Temporary Files
tmp/
temp/
*.tmp
*.temp
# Operating System Files
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db
(3) Git Hooks
▶ Example: pre-commit hook
#!/bin/bash
# .git/hooks/pre-commit
# Run Code Check
npm run lint
if [ $? -ne 0 ]; then
echo "❌ Code check failed,Please fix it and then submit it."
exit 1
fi
# Run Test
npm test
if [ $? -ne 0 ]; then
echo "❌ Test Failed,Please fix it and then submit it."
exit 1
fi
echo "✅ Code review and testing passed"
exit 0
6. Frequently Asked Questions and Solutions
(1) Handling Common Errors
▶ Example: Error Handling
# Error1:Push Rejected
git push origin main
# ! [rejected] main -> main (fetch first)
# Resolve:
git pull --rebase origin main
git push origin main
# Error2:Merge Conflicts
git merge feature
# CONFLICT (content): Merge conflict in file.js
# Resolve:
# Editing Files with Conflicts
git add file.js
git commit
# Error3:detached HEAD
git checkout a1b2c3d
# You are in 'detached HEAD' state
# Resolve:
git switch -c new-branch
# Error4:Accidentally Deleted a Branch
git branch -D feature
# Restore:
git reflog
git checkout -b feature <commit-id>
(2) Performance Optimization
▶ Example: Optimizing Git Performance
# Optimizing the Performance of Large Repositories
git gc --aggressive
# Partial Clone(Large Warehouse)
git clone --filter=blob:none --sparse <url>
git sparse-checkout init --cone
git sparse-checkout add src/
# Shallow Cloning(Only the most recent history is needed)
git clone --depth=1 <url>
# Disable File Mode Change Detection(Windows)
git config core.fileMode false
❓ FAQ
git rebase -i to merge related commits, use git pull --rebase instead of "merge," write clear commit messages, and avoid meaningless commits.rebase instead of merge.📖 Summary
- Commit Guidelines: Follow the Conventional Commits guidelines and write clear commit messages
- Branching strategies: Git Flow is suitable for projects with release cycles, while GitHub Flow is suitable for continuous deployment
- Workflow: Iterate quickly, commit frequently, sync regularly, and conduct code reviews
- Team Collaboration: PR review, conflict resolution, keeping the history clean
- Git Configuration: Set up aliases, credentials, and hooks to improve efficiency
- Best Practices: Standardized processes, clear communication, and continuous learning
📝 Exercises
-
Basic Exercises: Set up your Git environment, including user information, aliases, and an editor; create commit messages that follow best practices; and develop good Git usage habits.
-
Advanced Exercise: Implement the complete GitHub Flow workflow: create a feature branch, develop the feature, create a pull request (simulation), merge the branch, and clean up the branch to experience the team collaboration process.
-
Challenge: Write a Git user guide for the team, including commit guidelines, branching policies, workflows, and solutions to common issues, to help team members develop good Git habits.
🎉 Congratulations! You’ve completed the entire Git tutorial and mastered the core skills of version control!
Recommendations for Further Study:
- In-depth Study of Git's Internal Mechanisms
- Explore advanced features: submodules, worktrees, and filter branches
- Learn how to set up a Git server: GitLab, Gitea
- Learn about Git's integration with other tools: CI/CD, IDEs



