1.4 Git - Team UsageGit - 团队使用

Collaborative Development Workflows

👥 Team Git Overview

When working in teams, Git becomes a powerful collaboration tool. Team workflows enable multiple developers to work on the same codebase while maintaining quality and minimizing conflicts. 在团队协作中,Git 是强大的协作工具。合理的团队工作流能让多人并行开发同一代码库,同时保持代码质量并尽量减少冲突。

graph TD A[Team Git Workflow] --> B[Remote Repository] A --> C[Branching Strategy] A --> D[Pull Requests] A --> E[Code Review] A --> F[Conflict Resolution] B --> B1[Central codebase] B --> B2[Backup & sharing] C --> C1[Feature branches] C --> C2[Isolated development] D --> D1[Code integration] D --> D2[Quality control] E --> E1[Peer review] E --> E2[Knowledge sharing] F --> F1[Merge conflicts] F --> F2[Resolution strategies] style A fill:#e07a5f,stroke:#333,stroke-width:2px style B fill:#81b29a,stroke:#333,stroke-width:2px style C fill:#f2cc8f,stroke:#333,stroke-width:2px style D fill:#81b29a,stroke:#333,stroke-width:2px style E fill:#e07a5f,stroke:#333,stroke-width:2px style F fill:#f2cc8f,stroke:#333,stroke-width:2px

🌿 Team Branching Strategies

Feature Branch Workflow

The most common workflow for team development: 团队开发中最常见的工作流:

graph TD A[main] --> B[feature/user-auth] A --> C[feature/payment-gateway] A --> D[bugfix/login-issue] B --> E[PR #1] C --> F[PR #2] D --> G[PR #3] E --> A F --> A G --> A style A fill:#e07a5f,stroke:#333,stroke-width:2px style B fill:#81b29a,stroke:#333,stroke-width:2px style C fill:#f2cc8f,stroke:#333,stroke-width:2px style D fill:#81b29a,stroke:#333,stroke-width:2px style E fill:#f2cc8f,stroke:#333,stroke-width:2px style F fill:#f2cc8f,stroke:#333,stroke-width:2px style G fill:#f2cc8f,stroke:#333,stroke-width:2px
# Feature Branch Workflow Example

# 1. Create feature branch from latest main
git checkout main
git pull origin main
git checkout -b feature/user-authentication

# 2. Work on feature (multiple commits)
git add .
git commit -m "Add user authentication structure"
git add .
git commit -m "Implement login functionality"
git add .
git commit -m "Add password validation"

# 3. Keep branch updated with main
git checkout main
git pull origin main
git checkout feature/user-authentication
git merge main  # Resolve any conflicts

# 4. Push and create pull request
git push origin feature/user-authentication

# 5. After PR is approved and merged
git checkout main
git pull origin main
git branch -d feature/user-authentication

📋 Pull Requests (PRs)

Pull requests are the heart of team collaboration. They let team members review code, discuss changes, and ensure quality before merging. Pull Request 是团队协作的核心环节,让成员在合并前完成代码评审、讨论变更并保障质量。

Creating a Good Pull Request

# PR Template Example

## 🎯 Description
Brief description of what this PR accomplishes

## 🔄 Changes Made
- Added user authentication system
- Implemented JWT token handling
- Added password encryption
- Created login/logout endpoints

## 🧪 Testing
- [x] Unit tests pass
- [x] Integration tests pass
- [x] Manual testing completed
- [ ] Browser testing completed

## 📸 Screenshots (if applicable)


## 🔗 Related Issues
Closes #123
Related to #456

## 📝 Checklist
- [x] Code follows project standards
- [x] Documentation updated
- [x] Tests added/updated
- [x] No breaking changes

PR Review Process

# Code Review Best Practices

## For Reviewers:
1. **Be constructive** - Focus on code quality, not the person
2. **Be specific** - Point to exact lines and suggest improvements
3. **Be thorough** - Check for bugs, security issues, and performance
4. **Be kind** - Remember that someone put effort into this code

## Review Categories:
- **Functionality**: Does it work as expected?
- **Code Quality**: Is it clean, readable, and maintainable?
- **Testing**: Are there adequate tests?
- **Documentation**: Is the code well-documented?
- **Performance**: Are there any performance concerns?
- **Security**: Are there any security vulnerabilities?

## Example Review Comments:
❌ Bad: "This code is bad"
✅ Good: "Line 45: Consider using a constant for the timeout value instead of magic number"

❌ Bad: "Fix this"
✅ Good: "The error handling here could be improved. Consider adding logging for debugging"

⚔️ Merge Conflicts

Merge conflicts happen when Git cannot automatically reconcile differences between commits. Learning to resolve them is essential for team development. 当 Git 无法自动合并不同提交的差异时就会产生合并冲突。掌握冲突解决对团队开发至关重要。

Common Conflict Scenarios

graph TD A[Merge Conflict Types] --> B[Same line modified] A --> C[File deleted in one branch] A --> D[Branch diverged significantly] B --> B1[Both developers edit same line] B --> B2[Git can't decide which change to keep] C --> C1[File modified in one branch] C --> C2[File deleted in another] D --> D1[Many conflicting changes] D --> D2[Complex resolution needed] style A fill:#e07a5f,stroke:#333,stroke-width:2px style B fill:#81b29a,stroke:#333,stroke-width:2px style C fill:#f2cc8f,stroke:#333,stroke-width:2px style D fill:#81b29a,stroke:#333,stroke-width:2px

Resolving Conflicts

# Conflict Resolution Process

# 1. Identify the conflict
git merge feature-branch
# Output: CONFLICT (content): Merge conflict in filename.js

# 2. Open the conflicting file
# Look for conflict markers:
<<<<<<< HEAD
    // Your changes
    console.log("Hello from main");
=======
    // Their changes
    console.log("Hello from feature");
>>>>>>> feature-branch

# 3. Resolve the conflict manually
# Edit the file to keep the desired changes:
console.log("Hello from both branches");

# 4. Mark conflict as resolved
git add filename.js

# 5. Complete the merge
git commit -m "Resolve merge conflict"

# Alternative: Use merge tools
git mergetool  # Opens visual merge tool

Preventing Conflicts

# Best Practices to Avoid Conflicts

## 1. Communicate with team
- Use project management tools to track who's working on what
- Have daily standups to coordinate work
- Create design documents for complex features

## 2. Keep branches updated
git pull origin main          # Regularly pull latest changes
git merge main                # Merge main into your feature branch

## 3. Make small, focused commits
- Each commit should do one thing
- Write clear commit messages
- Review your own code before committing

## 4. Use feature flags
# Instead of merging incomplete features:
const FEATURE_ENABLED = true;

if (FEATURE_ENABLED) {
    // New feature code
}

## 5. Divide work by modules
- Work on different files/modules when possible
- Use interfaces to define boundaries
- Coordinate API changes with team

🔧 Team Git Commands

Remote Repository Management

# Working with remotes
git remote -v                           # Show all remotes
git remote add upstream            # Add upstream repository
git remote remove origin                # Remove a remote
git remote rename origin old-origin     # Rename a remote

# Fetching from remotes
git fetch origin                        # Fetch all branches
git fetch origin main                   # Fetch specific branch
git pull --rebase origin main           # Pull with rebase

# Pushing to remotes
git push origin main                   # Push to remote
git push -u origin main                # Set upstream and push
git push --force-with-lease origin main # Safe force push

Advanced Team Commands

# Rebasing (cleaner history)
git rebase main                        # Rebase current branch onto main
git rebase -i HEAD~3                   # Interactive rebase (edit/squash commits)

# Stashing (save work temporarily)
git stash                              # Save current work
git stash pop                          # Apply and remove stash
git stash list                         # Show all stashes
git stash clear                        # Clear all stashes

# Cherry-picking (apply specific commits)
git cherry-pick commit-hash            # Apply specific commit to current branch

# Bisecting (find problematic commit)
git bisect start                       # Start bisect
git bisect bad                         # Mark current commit as bad
git bisect good commit-hash            # Mark commit as good
git bisect reset                       # End bisect

🔄 Popular Team Workflows

GitHub Flow

Simple workflow focused on continuous deployment: 以持续部署为核心的简洁工作流:

# GitHub Flow Steps:
1. Create branch from main
2. Make changes and commit
3. Open pull request
4. Discuss and review code
5. Deploy to staging
6. Merge to main
7. Deploy to production

GitFlow

More structured workflow for larger projects: 更适合大型项目的结构化工作流:

graph TD A[main] --> B[develop] B --> C[feature/*] B --> D[release/*] A --> E[hotfix/*] C --> B D --> A D --> B E --> A E --> B style A fill:#e07a5f,stroke:#333,stroke-width:2px style B fill:#81b29a,stroke:#333,stroke-width:2px style C fill:#f2cc8f,stroke:#333,stroke-width:2px style D fill:#81b29a,stroke:#333,stroke-width:2px style E fill:#f2cc8f,stroke:#333,stroke-width:2px
# GitFlow Commands:

# Create feature branch
git checkout develop
git checkout -b feature/new-feature

# Finish feature
git checkout develop
git merge feature/new-feature
git branch -d feature/new-feature

# Create release branch
git checkout develop
git checkout -b release/v1.0.0

# Finish release
git checkout main
git merge release/v1.0.0
git tag -a v1.0.0 -m "Version 1.0.0"
git checkout develop
git merge release/v1.0.0
git branch -d release/v1.0.0

# Create hotfix branch
git checkout main
git checkout -b hotfix/critical-bug

# Finish hotfix
git checkout main
git merge hotfix/critical-bug
git tag -a v1.0.1 -m "Version 1.0.1"
git checkout develop
git merge hotfix/critical-bug
git branch -d hotfix/critical-bug

✅ Team Best Practices

📝 Commit Guidelines

  • Write clear, descriptive commit messages
  • Keep commits small and focused
  • Use present tense ("Add feature" not "Added")
  • Include issue numbers in commit messages
  • Review your commits before pushing

🌿 Branch Management

  • Delete merged branches regularly
  • Use descriptive branch names
  • Keep branches focused on single features
  • Regularly sync with main branch
  • Protect main branch from direct pushes

📋 Pull Request Process

  • Write detailed PR descriptions
  • Include testing instructions
  • Respond to review comments promptly
  • Ensure CI/CD checks pass
  • Get at least one approval before merging

🤝 Team Communication

  • Communicate about overlapping work
  • Use project management tools
  • Have regular sync meetings
  • Document decisions and processes
  • Be respectful in code reviews

🎬 Example Team Scenario

Let's walk through a realistic team scenario where multiple developers collaborate on a web application: 下面以一个真实的团队场景为例,演示多名开发者如何协作完成一个 Web 应用:

# Team Scenario: E-commerce Website

## Team Members:
- Alice: Frontend Developer (working on user profile page)
- Bob: Backend Developer (working on user authentication)
- Charlie: DevOps Engineer (working on deployment pipeline)

## Day 1: Setup and Planning
# Alice creates frontend branch
git checkout main
git pull origin main
git checkout -b feature/user-profile-page

# Bob creates backend branch
git checkout main
git pull origin main
git checkout -b feature/user-auth-backend

# Charlie creates devops branch
git checkout main
git pull origin main
git checkout -b feature/ci-cd-pipeline

## Day 2: Development
# Alice works on frontend
git add .
git commit -m "Add user profile page structure"
git add .
git commit -m "Implement profile picture upload"

# Bob works on backend
git add .
git commit -m "Create user authentication API"
git add .
git commit -m "Add JWT token handling"

# Charlie works on CI/CD
git add .
git commit -m "Set up GitHub Actions workflow"
git add .
git commit -m "Add automated testing pipeline"

## Day 3: Integration
# Alice needs Bob's API endpoints
git pull origin main                # Get latest changes
git merge main                     # Merge main into her branch
# Resolves any conflicts

# Bob finishes his feature
git add .
git commit -m "Complete authentication system"
git push origin feature/user-auth-backend
# Creates PR for review

## Day 4: Review and Merge
# Team reviews Bob's PR
# After approval, PR is merged to main
git checkout main
git pull origin main
git branch -d feature/user-auth-backend

# Alice updates her branch
git pull origin main
git merge main
# Continues development

## Day 5: Final Integration
# All features complete
# All PRs merged to main
# Team prepares for deployment

📋 Summary总结

💭 Thinking Thinking & Practice Practice思考与实践