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:

(2) Conventional Commits Standard

This is the most popular commit message convention currently:

TEXT
<type>(<scope>): <subject>

<body>

<footer>

Explanation of Each Section:

(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

BASH
# 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:

TEXT
feat(auth): AddOAuth2.0Login Support

- SupportGoogle、GitHub、WeChat Third-Party Login
- Add Login State Persistence
- Enable Auto-RefreshTokenMechanism

Closes #456

Poor commit messages:

TEXT
update
fix bug
I made a few changes.
WIP
asdfasdf

Best Practices:


2. Branching Strategy

(1) The Git Flow Model

Git Flow is the most classic branching strategy:

100%
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:

▶ Example: Git Flow Workflow

BASH
# 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:

100%
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:

▶ Example: GitHub Flow Workflow

BASH
# 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

100%
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

BASH
# 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

BASH
# 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:

When reviewing a PR:

▶ Example: PR Description Template

MARKDOWN
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

BASH
# 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

BASH
# 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

▶ Example: Configuring Git

BASH
# 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

TEXT
# 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

BASH
#!/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

BASH
# 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

BASH
# 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

Q How can I keep my commit history clean?
A Use git rebase -i to merge related commits, use git pull --rebase instead of "merge," write clear commit messages, and avoid meaningless commits.
Q Which should I use, Git Flow or GitHub Flow?
A Git Flow is suitable for projects with a defined release cycle, while GitHub Flow is suitable for projects with continuous deployment. For small projects, GitHub Flow is recommended as it is simpler and more efficient.
Q How should we approach long-term feature development?
A Regularly merge updates from main/develop to stay in sync, use feature flags to control feature activation, and break down major features into smaller pull requests for gradual merging.
Q How can I avoid merge conflicts?
A Synchronize remote code frequently, take small, rapid steps with frequent commits, communicate promptly to coordinate the scope of changes, and use rebase instead of merge.
Q In what language should the information be submitted?
A We recommend using English, as it complies with international standards and facilitates open-source collaboration. Chinese may be used for internal team projects, but consistency must be maintained.

📖 Summary


📝 Exercises

  1. 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.

  2. 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.

  3. 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:

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏