1. Git 版本控制概述
🎯 核心价值
- 代码版本追踪与管理
- 多人协作开发支持
- 代码变更历史审计
- 分支并行开发能力
- 代码回滚与恢复
🏢 企业级特性
- 细粒度权限控制
- 代码审查流程
- CI/CD 集成
- 问题追踪管理
- 容器镜像仓库
🔐 安全保障
- SSH 密钥认证
- 双因素认证(2FA)
- 保护分支规则
- 代码签名验证
- 审计日志记录
📊 平台对比
- GitLab:一体化 DevOps
- GitHub:最大开源社区
- Gitee:国内访问快速
- Bitbucket:Atlassian 生态
- Azure DevOps:微软生态
2. Git 工作流对比与选择
🌳 GitFlow 工作流
适合有固定发布周期的项目,结构清晰但相对复杂。
- main/master:生产分支
- develop:开发集成分支
- feature/*:功能分支
- release/*:发布分支
- hotfix/*:热修复分支
适用场景:
• 传统软件发布模式
• 多版本并行维护
• 严格的质量管控
• 传统软件发布模式
• 多版本并行维护
• 严格的质量管控
🚀 GitHub Flow
简单轻量,适合持续部署的互联网项目。
- main:唯一长期分支
- feature/*:功能分支
- Pull Request 审查
- 直接部署到生产
适用场景:
• SaaS 持续部署
• 小型敏捷团队
• 快速迭代产品
• SaaS 持续部署
• 小型敏捷团队
• 快速迭代产品
🌲 Trunk Based Development
现代 DevOps 推荐,短生命周期分支。
- trunk/main:主干分支
- 短命 feature 分支(<2 天)
- 频繁小批量提交
- 功能开关控制
适用场景:
• 成熟 DevOps 团队
• 高频率发布需求
• 自动化测试完善
• 成熟 DevOps 团队
• 高频率发布需求
• 自动化测试完善
🍴 GitLab Flow
GitFlow 和 GitHub Flow 的折中方案。
- main:主干分支
- pre-production:预发布
- production:生产环境
- environment/*:环境分支
适用场景:
• 多环境部署需求
• 需要环境隔离
• 中等规模团队
• 多环境部署需求
• 需要环境隔离
• 中等规模团队
💡 工作流选择建议:
- 传统企业/金融/政府项目:GitFlow(严格管控、多版本维护)
- 互联网 SaaS/创业公司:GitHub Flow 或 Trunk Based(快速迭代)
- 中大型团队/多环境:GitLab Flow(平衡灵活性与规范性)
- 本指南重点讲解 GitFlow:因其结构最完整,其他工作流可参考简化
3. GitLab 仓库创建与配置
步骤 1:创建项目(Group & Project)
# ===== Web 界面操作 =====
1. 登录 GitLab → 左上角「+」→ New project
2. 选择「Create blank project」
# ===== 项目信息配置 =====
Project name: backend-service
Project slug: backend-service # 自动生成,可修改
Project description: 后端微服务 - 用户中心
Visibility level: Private # Internal/Public 根据需求选择
# ===== 选择命名空间(Group)=====
Namespace: your-company / engineering-team
# 如果没有合适的 Group,先创建 Group:
左上角「+」→ New group → 填写组名和描述
# ===== 初始化选项 =====
☑ Add a README file # 推荐勾选,便于后续克隆
☐ Add .gitignore # 可选择语言模板,如 Java/Maven
☐ Add a license # 开源项目选择 MIT/Apache 2.0
# 点击「Create project」完成创建
步骤 2:配置项目设置
# ===== 常规设置 =====
路径:Settings → General
Visibility, project features, permissions:
- Wiki: Enabled
- Issues: Enabled
- Merge requests: Enabled
- Packages: Enabled
- Container Registry: Enabled
Merge requests:
- Merge method: Merge commits with semi-linear history
- Show merge request reference in commit messages: ✓
- Pipelines must succeed: ✓ # 强制 CI 通过才能合并
- All threads must be resolved: ✓ # 所有评论必须解决
Merge request approvals:
- Approvals required: 2 # 至少 2 人审批
- Prevent approval by author: ✓ # 作者不能自批
- Prevent approval without sufficient users: ✓
# ===== 仓库设置 =====
路径:Settings → Repository
Default branch: develop # 设置为 develop 而非 main
Push rules:
- Prevent committing secrets to Git: ✓ # 密钥检测
- Prevent committing large files: ✓ # 限制大文件
- Maximum file size (MB): 10
- Check for commit message: ✓
- Commit message regex: ^(feat|fix|docs|style|refactor|test|chore)\(.+\): .+
# ===== 集成设置 =====
路径:Settings → Webhooks
URL: http://jenkins.yourcompany.com/project/webhook/
Secret Token: your-webhook-secret-token
Trigger: Push events, Merge request events
点击「Add webhook」
步骤 3:配置保护分支
# ===== 路径:Settings → Repository → Protected branches =====
# 1. 保护 main 分支(生产分支)
Branch: main
Allowed to merge: Maintainers + Developers
Allowed to push: No one # 禁止直接推送
Allowed to force push: ✗ # 禁止强制推送
点击「Protect」
# 2. 保护 develop 分支(开发分支)
Branch: develop
Allowed to merge: Maintainers + Developers
Allowed to push: Developers + Maintainers
Allowed to force push: ✗
点击「Protect」
# 3. 保护 release 分支(发布分支)
Branch: release/*
Allowed to merge: Maintainers
Allowed to push: Maintainers
Allowed to force push: ✗
点击「Protect」
# 4. 保护 hotfix 分支(热修复分支)
Branch: hotfix/*
Allowed to merge: Maintainers
Allowed to push: Maintainers + Developers
Allowed to force push: ✗
点击「Protect」
步骤 4:添加团队成员与权限
# ===== 路径:Manage → Members =====
# 角色说明:
Guest: 只能查看 Issues、MR 评论
Reporter: 可以查看代码、创建 Issue、MR
Developer: 可以创建分支、推送代码、管理 MR
Maintainer: 可以管理项目设置、保护分支、合并 MR
Owner: 完全控制(包括删除项目)
# 添加团队成员示例:
Member 1:
- Username: zhangsan
- Role: Maintainer # 技术负责人
- Access expiration: Leave empty # 永久
Member 2:
- Username: lisi
- Role: Developer # 后端开发
Member 3:
- Username: wangwu
- Role: Developer # 前端开发
Member 4:
- Username: zhaoliu
- Role: Reporter # 测试人员
# 邀请外部协作者:
Invite members: external@example.com
Role: Guest
Message: 邀请您参与项目代码审查
步骤 5:本地克隆与初始化
# ===== 克隆项目到本地 =====
cd /workspace/projects
git clone git@gitlab.yourcompany.com:your-company/backend-service.git
cd backend-service
# ===== 配置 Git 用户信息 =====
git config user.name "张三"
git config user.email "zhangsan@yourcompany.com"
# ===== 创建并推送 develop 分支 =====
git checkout -b develop
git push -u origin develop
# ===== 创建 .gitignore 文件 =====
cat > .gitignore << 'EOF'
# Compiled files
*.class
*.jar
*.war
target/
build/
dist/
# Dependencies
node_modules/
vendor/
# IDE
.idea/
.vscode/
*.iml
*.swp
*.swo
# Logs
*.log
logs/
# OS
.DS_Store
Thumbs.db
# Environment
.env
.env.local
*.local
# Secrets
*.pem
*.key
secrets/
EOF
git add .gitignore
git commit -m "chore: add .gitignore file"
git push origin develop
4. GitHub 仓库创建与配置
步骤 1:创建 Organization 和 Repository
# ===== 创建组织(Organization)=====
1. 点击右上角头像 → Your organizations
2. 点击「New organization」
3. 选择计划(Free/Team/Enterprise)
Organization name: your-company
Billing email: finance@yourcompany.com
Organization email: admin@yourcompany.com
# ===== 创建仓库(Repository)=====
1. 进入组织页面 → Repositories → New repository
Repository name: backend-service
Description: 后端微服务 - 用户中心
Visibility: Private # Public/Internal 根据需要选择
Initialize this repository with:
☑ Add a README file
☐ Add .gitignore # 可选择语言模板
☐ Choose a license
点击「Create repository」
步骤 2:配置 Branch Protection Rules
# ===== 路径:Settings → Branches → Add branch protection rule =====
# 1. 保护 main 分支
Branch name pattern: main
☑ Require a pull request before merging
- Required approvals: 2
- ☑ Dismiss stale pull request approvals when new commits are pushed
- ☑ Require review from Code Owners
☑ Require status checks to pass before merging
- Status checks that are required: ci/jenkins, sonarqube-check
☑ Require branches to be up to date before merging
☑ Include administrators # 管理员也要遵守规则
☑ Do not allow bypassing the above settings
☑ Restrict who can push to matching branches
- Restrict pushes: Maintainers only
☑ Allow force pushes? ✗ # 禁止强制推送
☑ Allow deletions? ✗ # 禁止删除分支
点击「Create」
# 2. 保护 develop 分支
Branch name pattern: develop
☑ Require a pull request before merging
- Required approvals: 1
☑ Require status checks to pass before merging
- Status checks: ci/jenkins
☑ Include administrators
☑ Restrict who can push to matching branches
- Restrict pushes: Developers + Maintainers
点击「Create」
# 3. 保护 release 和 hotfix 分支
Branch name pattern: release/*
☑ Require a pull request before merging
- Required approvals: 2
☑ Require status checks to pass before merging
☑ Restrict who can push to matching branches
- Restrict pushes: Maintainers only
Branch name pattern: hotfix/*
☑ Require a pull request before merging
- Required approvals: 1
☑ Require status checks to pass before merging
☑ Restrict who can push to matching branches
- Restrict pushes: Maintainers + Developers
步骤 3:配置 CODEOWNERS 文件
# ===== 在仓库根目录创建 .github/CODEOWNERS =====
mkdir -p .github
cat > .github/CODEOWNERS << 'EOF'
# 全局默认审核人
* @tech-lead @backend-team
# 后端代码由后端团队审核
/src/main/java/ @backend-team
/src/main/resources/ @backend-team
# 前端代码由前端团队审核
/src/main/frontend/ @frontend-team
/public/ @frontend-team
# 配置文件由运维团队审核
/docker/ @devops-team
/kubernetes/ @devops-team
Jenkinsfile @devops-team
# 文档由技术写作团队审核
/docs/ @tech-writer
# 特定模块的专属审核人
/src/main/java/com/company/security/ @security-team @zhangsan
/src/main/java/com/company/payment/ @payment-team @lisi
EOF
git add .github/CODEOWNERS
git commit -m "chore: add CODEOWNERS file"
git push origin develop
# CODEOWNERS 格式说明:
# * 表示所有文件
# 路径可以是目录或文件通配符
# @username 或 @team-name 指定审核人
# 多个审核人用空格分隔
步骤 4:添加协作者与团队权限
# ===== 添加个人协作者 =====
路径:Settings → Collaborators and teams → Add people
Username: zhangsan
Role: Write # Read/Write/Admin
# ===== 创建团队(Team)=====
路径:Teams → New team
Team name: backend-team
Description: 后端开发团队
Privacy: Visible # Secret/Visible
Repository access: Select repositories → backend-service
Permission: Write
# 添加成员到团队:
进入 backend-team → Members → Add a member
Members: zhangsan, lisi, wangwu
# ===== 角色权限说明 =====
Read: 查看代码、Issues、MR
Write: 创建分支、推送代码、管理 MR
Maintain: 管理仓库设置、保护分支
Triage: 管理 Issues、MR(不能推送代码)
Admin: 完全控制(包括删除仓库)
5. GitFlow 分支模型详解
5.1 GitFlow 分支架构图
┌─────────────────────────────────────────────────────────────────┐
│ GitFlow Branch Model │
├─────────────────────────────────────────────────────────────────┤
│ │
│ main (master) ──●───────────────────────●───────────────● │
│ │ │ │ │
│ │ v1.0.0 │ v1.1.0 │ │
│ │ [TAG] │ [TAG] │ │
│ │ │ │ │
│ develop ────────○───────●───────●───────○───────●───────○ │
│ │ │ │ │ │ │ │
│ │ ┌───┘ │ ┌───┘ │ ┌───┘ │
│ │ │ │ │ │ │ │
│ feature/login │ ●─●─● │ │ │ │ │
│ │ / │ │ │ │ │
│ feature/api │●─●─●─● │ │ │ │ │
│ │ │ │ │ │ │
│ release/v1.0 │ ○───●───● │ │ │
│ │ │ │ │ │ │
│ release/v1.1 │ │ │ ○───●─● │
│ │ │ │ │ │
│ hotfix/bug-fix │ │ ●───────────┘ │
│ │ │ / │
│ │ │ / │
│ │ ● │
│ │
│ 图例说明: │
│ ● Commit 提交点 │
│ ○ 分支合并点 │
│ ─── 分支线 │
│ [TAG] 版本标签 │
│ │
│ 分支类型: │
│ • main: 生产环境分支,只接受 release 和 hotfix 合并 │
│ • develop: 开发集成分支,所有 feature 的最终目标 │
│ • feature/*: 功能开发分支,从 develop 分出,完成后合并回 develop │
│ • release/*: 发布准备分支,从 develop 分出,完成后合并到 main 和 develop │
│ • hotfix/*: 紧急修复分支,从 main 分出,完成后合并到 main 和 develop │
│ │
└─────────────────────────────────────────────────────────────────┘
5.2 安装 git-flow 扩展工具
# ===== Linux (Ubuntu/Debian) =====
sudo apt-get install git-flow
# ===== macOS (Homebrew) =====
brew install git-flow-avh
# ===== CentOS/RHEL =====
sudo yum install git-flow
# ===== Windows (Git Bash) =====
# 下载:https://github.com/gitflow-windows/gitflow-installer/releases
git-flow version
# ===== 在项目初始化 git-flow =====
cd /workspace/projects/backend-service
git flow init
# 交互式配置:
Branch name for production releases: [main] # 回车默认
Branch name for "next release" development: [develop] # 回车默认
Feature branches? [feature/] # 回车默认
Release branches? [release/] # 回车默认
Hotfix branches? [hotfix/] # 回车默认
Support branches? [support/] # 回车默认
Version tag prefix? [] # 回车默认
# 初始化后会自动创建 develop 分支并切换到该分支
git branch -a
# * develop
# main
5.3 Feature 分支开发流程
# ===== 开始一个新功能开发 =====
# 1. 从 develop 创建 feature 分支
git flow feature start user-authentication
# 等价于:git checkout -b feature/user-authentication develop
# 2. 进行开发并提交
git add src/main/java/com/company/auth/
git commit -m "feat(auth): implement JWT token authentication"
git add src/test/java/com/company/auth/
git commit -m "test(auth): add unit tests for JWT auth"
# 3. 推送到远程仓库
git flow feature publish user-authentication
# 等价于:git push -u origin feature/user-authentication
# 4. 同步最新 develop 分支(避免冲突)
git flow feature pull user-authentication
# 或者手动:git fetch origin && git merge origin/develop
# 5. 完成功能开发并合并到 develop
git flow feature finish user-authentication
# 等价于:
# git checkout develop
# git merge --no-ff feature/user-authentication
# git branch -d feature/user-authentication
# git push origin develop
# 6. 在 GitLab/GitHub 创建 Merge Request / Pull Request
# 等待代码审查通过后合并
5.4 Release 分支发布流程
# ===== 准备新版本发布 =====
# 1. 从 develop 创建 release 分支
git flow release start 1.0.0
# 等价于:git checkout -b release/1.0.0 develop
# 2. 进行发布前的最后调整(只修复 bug,不加新功能)
git add pom.xml
git commit -m "chore: bump version to 1.0.0-RELEASE"
git add docs/CHANGELOG.md
git commit -m "docs: update changelog for v1.0.0"
# 3. 推送到远程仓库
git flow release publish 1.0.0
# 等价于:git push -u origin release/1.0.0
# 4. 测试验证(运行完整的测试套件)
# CI/CD 流水线会自动触发
# 5. 完成发布(合并到 main 和 develop,打标签)
git flow release finish 1.0.0
# 等价于:
# git checkout main
# git merge --no-ff release/1.0.0
# git tag -a v1.0.0 -m "Release version 1.0.0"
# git checkout develop
# git merge --no-ff release/1.0.0
# git branch -d release/1.0.0
# git push origin main develop --tags
# 6. 在 GitLab/GitHub 创建 Release Note
# 包含新功能列表、Bug 修复、已知问题等
5.5 Hotfix 分支紧急修复流程
# ===== 生产环境紧急 Bug 修复 =====
# 1. 从 main 创建 hotfix 分支
git flow hotfix start 1.0.1
# 等价于:git checkout -b hotfix/1.0.1 main
# 2. 修复紧急 Bug
git add src/main/java/com/company/auth/SecurityFilter.java
git commit -m "fix(security): resolve authentication bypass vulnerability"
# 3. 推送到远程仓库
git flow hotfix publish 1.0.1
# 等价于:git push -u origin hotfix/1.0.1
# 4. 创建紧急 MR/PR,快速审查
# 通知相关人员优先审查
# 5. 完成热修复(合并到 main 和 develop)
git flow hotfix finish 1.0.1
# 等价于:
# git checkout main
# git merge --no-ff hotfix/1.0.1
# git tag -a v1.0.1 -m "Hotfix version 1.0.1"
# git checkout develop
# git merge --no-ff hotfix/1.0.1
# git branch -d hotfix/1.0.1
# git push origin main develop --tags
# 6. 立即部署到生产环境
# 触发 CI/CD 流水线自动部署
6. 保护分支规则配置
6.1 GitLab 保护分支高级配置
# ===== 使用 GitLab API 配置保护分支 =====
# 1. 获取项目 ID
curl --header "PRIVATE-TOKEN: your-access-token" \\
"https://gitlab.yourcompany.com/api/v4/projects?search=backend-service"
project_id="12345"
# 2. 保护 main 分支
curl --request POST --header "PRIVATE-TOKEN: your-access-token" \\
"https://gitlab.yourcompany.com/api/v4/projects/${project_id}/protected_branches" \\
--data "name=main" \\
--data "allowed_to_push[]=access_level:0" \\
--data "allowed_to_merge[]=access_level:30" \\
--data "allowed_to_force_push=false" \\
--data "is_default=true"
# 3. 保护 develop 分支
curl --request POST --header "PRIVATE-TOKEN: your-access-token" \\
"https://gitlab.yourcompany.com/api/v4/projects/${project_id}/protected_branches" \\
--data "name=develop" \\
--data "allowed_to_push[]=access_level:30" \\
--data "allowed_to_merge[]=access_level:30" \\
--data "allowed_to_force_push=false"
# 4. 使用通配符保护 release 分支
curl --request POST --header "PRIVATE-TOKEN: your-access-token" \\
"https://gitlab.yourcompany.com/api/v4/projects/${project_id}/protected_branches" \\
--data "name=release/*" \\
--data "allowed_to_push[]=access_level:40" \\
--data "allowed_to_merge[]=access_level:40" \\
--data "allowed_to_force_push=false"
# 访问级别说明:
# 0: No access
# 10: Guest
# 20: Reporter
# 30: Developer
# 40: Maintainer
# 50: Owner
6.2 GitHub 分支保护规则 API
# ===== 使用 GitHub API 配置分支保护 =====
OWNER="your-company"
REPO="backend-service"
TOKEN="ghp_xxxxxxxxxxxxxxxxxxxx"
# 1. 保护 main 分支
curl -X PUT \\
-H "Authorization: token ${TOKEN}" \\
-H "Accept: application/vnd.github.v3+json" \\
https://api.github.com/repos/${OWNER}/${REPO}/branches/main/protection \\
-d '{
"required_status_checks": {
"strict": true,
"contexts": ["ci/jenkins", "sonarqube-check"]
},
"enforce_admins": true,
"required_pull_request_reviews": {
"required_approving_review_count": 2,
"dismiss_stale_reviews": true,
"require_code_owner_reviews": true,
"dismissal_restrictions": {
"users": [],
"teams": ["tech-leads"]
}
},
"restrictions": {
"users": [],
"teams": ["maintainers"],
"apps": []
},
"allow_force_pushes": false,
"allow_deletions": false,
"block_creations": false,
"required_linear_history": true,
"allow_fork_syncing": false
}'
# 2. 保护 develop 分支
curl -X PUT \\
-H "Authorization: token ${TOKEN}" \\
-H "Accept: application/vnd.github.v3+json" \\
https://api.github.com/repos/${OWNER}/${REPO}/branches/develop/protection \\
-d '{
"required_status_checks": {
"strict": true,
"contexts": ["ci/jenkins"]
},
"enforce_admins": true,
"required_pull_request_reviews": {
"required_approving_review_count": 1
},
"restrictions": {
"users": [],
"teams": ["developers", "maintainers"],
"apps": []
},
"allow_force_pushes": false,
"allow_deletions": false
}'
6.3 推送规则(Push Rules)配置
# ===== GitLab 推送规则配置 =====
路径:Settings → Repository → Push rules
Secret token: your-push-rule-secret
URL: http://jenkins.yourcompany.com/gitlab-push-hook/
Prevent committing secrets to Git: ✓
# 检测 AWS Access Key、Private Key、Password 等敏感信息
Prevent committing large files: ✓
Maximum file size (MB): 10
# 防止大文件污染仓库
Check for commit message: ✓
Commit message regex:
^(feat|fix|docs|style|refactor|perf|test|chore|revert|merge)\\([a-zA-Z0-9_-]+\\): .{10,200}$
# 强制使用约定式提交规范
Reject unsigned commits: ✓
# 要求 GPG 签名提交
Do not allow users to remove git tags: ✓
# 防止删除标签
Check whether author is a GitLab user: ✓
# 确保提交者邮箱与 GitLab 账户匹配
Always check for merge commits: ✗
# 不强制要求合并提交
Name of default branch: main
# 指定默认分支名称
点击「Add push rule」保存
7. Merge Request / Pull Request
7.1 GitLab Merge Request 模板
# ===== 创建 .gitlab/merge_request_templates/default.md =====
mkdir -p .gitlab/merge_request_templates
cat > .gitlab/merge_request_templates/default.md << 'EOF'
## 📋 变更类型
- [ ] 🚀 新功能 (feat)
- [ ] 🐛 Bug 修复 (fix)
- [ ] 📝 文档更新 (docs)
- [ ] 🎨 代码样式 (style)
- [ ] ♻️ 代码重构 (refactor)
- [ ] ⚡ 性能优化 (perf)
- [ ] ✅ 测试用例 (test)
- [ ] 🔧 构建配置 (chore)
- [ ] ⏪ 回退更改 (revert)
## 🎯 关联 Issue
Closes #ISSUE_NUMBER
## 📝 变更描述
请详细描述此 MR 的目的、实现方式和影响范围。
### 背景
### 实现方案
### 影响范围
## ✅ 自查清单
- [ ] 代码已通过本地编译
- [ ] 已添加必要的单元测试
- [ ] 所有测试用例已通过
- [ ] 已更新相关文档
- [ ] 无新的 SonarQube 问题
- [ ] 无敏感信息泄露(密码、Token 等)
- [ ] 遵循项目代码规范
## 🧪 测试说明
### 测试环境
- 环境:Dev / Test / Staging
- 浏览器/设备:Chrome 120 / iPhone 15 Pro
### 测试步骤
1.
2.
3.
### 预期结果
### 实际结果
## 📸 截图(如适用)
## 📋 Reviewer 注意事项
- [ ] 核心逻辑是否正确
- [ ] 是否存在安全隐患
- [ ] 性能是否有影响
- [ ] 是否需要补充测试
---
**提交前请确保:**
1. 已 rebase 到最新 develop 分支
2. Commit 信息符合规范
3. CI 流水线全部通过
EOF
git add .gitlab/merge_request_templates/
git commit -m "docs: add merge request template"
git push origin develop
7.2 GitHub Pull Request 模板
# ===== 创建 .github/pull_request_template.md =====
mkdir -p .github
cat > .github/pull_request_template.md << 'EOF'
## 🎫 Ticket
Fixes #ISSUE_NUMBER
## 📝 Description
### Type of Change
- [ ] 🚀 New feature (non-breaking change which adds functionality)
- [ ] 🐛 Bug fix (non-breaking change which fixes an issue)
- [ ] 💥 Breaking change (fix or feature that would cause existing functionality to not work as expected)
- [ ] 📝 Documentation update
- [ ] 🎨 Code style update
- [ ] ♻️ Code refactoring
- [ ] ⚡ Performance improvement
- [ ] ✅ Test addition/update
- [ ] 🔧 Build configuration change
- [ ] ⏪ Revert
## 🧪 Testing
### Test Coverage
- [ ] Unit tests added/updated
- [ ] Integration tests added/updated
- [ ] E2E tests added/updated
- [ ] Manual testing performed
### Test Instructions
1.
2.
3.
### Screenshots/Videos (if applicable)
## ✅ Checklist
- [ ] My code follows the project's style guidelines
- [ ] I have performed a self-review of my code
- [ ] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [ ] My changes generate no new warnings
- [ ] I have added tests that prove my fix is effective or that my feature works
- [ ] New and existing unit tests pass locally with my changes
- [ ] Any dependent changes have been merged and published
- [ ] No secrets or sensitive data committed
## 📋 Notes for Reviewers
## 🔗 Related PRs
---
**Before merging, please ensure:**
1. All CI checks are passing
2. At least 2 approvals from maintainers
3. All comments are resolved
4. Branch is up to date with develop
EOF
git add .github/pull_request_template.md
git commit -m "docs: add pull request template"
git push origin develop
7.3 创建 Merge Request / Pull Request
# ===== GitLab 创建 MR =====
# 方法 1: Web 界面
1. 访问项目页面 → Merge requests → New merge request
2. Source branch: feature/user-authentication
3. Target branch: develop
4. 填写标题和描述(会自动加载模板)
5. 选择 Assignee 和 Reviewers
6. 点击「Create merge request」
# 方法 2: GitLab CLI
glab mr create \\
--title "feat(auth): implement JWT token authentication" \\
--description-file .gitlab/mr_description.md \\
--assignee zhangsan \\
--reviewer lisi,wangwu \\
--label "feature,authentication" \\
--milestone "v1.0.0"
# 方法 3: GitLab API
curl --request POST --header "PRIVATE-TOKEN: your-token" \\
"https://gitlab.yourcompany.com/api/v4/projects/12345/merge_requests" \\
--data "title=feat(auth): implement JWT authentication" \\
--data "description=Implement JWT-based authentication..." \\
--data "source_branch=feature/user-authentication" \\
--data "target_branch=develop" \\
--data "assignee_ids[]=100" \\
--data "reviewer_ids[]=101,102"
# ===== GitHub 创建 PR =====
# 方法 1: Web 界面
1. 访问仓库 → Pull requests → New pull request
2. base: develop ← compare: feature/user-authentication
3. 填写标题和描述(会自动加载模板)
4. 选择 Reviewers、Labels、Projects、Milestone
5. 点击「Create pull request」
# 方法 2: GitHub CLI
gh pr create \\
--title "feat(auth): implement JWT token authentication" \\
--body-file .github/pr_description.md \\
--base develop \\
--head feature/user-authentication \\
--assignee zhangsan \\
--reviewer lisi,wangwu \\
--label "feature,authentication" \\
--milestone "v1.0.0"
# 方法 3: GitHub API
curl -X POST \\
-H "Authorization: token ${TOKEN}" \\
-H "Accept: application/vnd.github.v3+json" \\
https://api.github.com/repos/${OWNER}/${REPO}/pulls \\
-d '{
"title": "feat(auth): implement JWT authentication",
"body": "Implement JWT-based authentication...",
"head": "feature/user-authentication",
"base": "develop",
"assignees": ["zhangsan"],
"reviewers": ["lisi", "wangwu"],
"labels": ["feature", "authentication"],
"milestone": 1
}'
8. 代码审查最佳实践
8.1 代码审查清单
✅ 代码质量
- 代码是否简洁清晰?
- 是否遵循编码规范?
- 函数/方法是否单一职责?
- 变量/函数命名是否有意义?
- 是否有重复代码(DRY)?
🔒 安全性
- 是否有 SQL 注入风险?
- 是否有 XSS/CSRF 漏洞?
- 敏感数据是否加密存储?
- 认证授权逻辑是否正确?
- 是否泄露密钥/Token?
⚡ 性能
- 是否有 N+1 查询问题?
- 是否有内存泄漏风险?
- 循环是否有优化空间?
- 缓存使用是否合理?
- 数据库索引是否有效?
🧪 测试
- 是否添加了单元测试?
- 测试覆盖率是否达标?
- 边界条件是否测试?
- 异常场景是否覆盖?
- 测试用例是否独立可重复?
8.2 代码审查流程
# ===== 标准代码审查流程 =====
阶段 1: 自动检查(CI/CD 流水线)
├─ 代码编译构建
├─ 单元测试执行
├─ 代码静态分析(SonarQube)
├─ 安全扫描(SAST/DAST)
├─ 代码格式化检查
└─ 许可证合规检查
阶段 2: 同行评审(Peer Review)
├─ 分配 Reviewer(1-2 人)
├─ Reviewer 审查代码
├─ 提出问题和建议
├─ 作者回复并修改
└─ 循环直到所有问题解决
阶段 3: 技术负责人审批
├─ Tech Lead 最终审核
├─ 确认架构设计合理性
├─ 评估对系统的影响
└─ 批准合并
阶段 4: 合并与部署
├─ Squash & Merge / Merge Commit
├─ 删除源分支
├─ 触发部署流水线
└─ 验证部署结果
# ===== 审查时间要求 =====
普通 MR/PR: 24-48 小时内完成审查
紧急 Hotfix: 2-4 小时内完成审查
大型重构: 3-5 天内分批次审查
# ===== 审查意见分类 =====
[Blocking]: 必须修复,否则不能合并
[Non-blocking]: 建议修复,不影响合并
[Question]: 询问,需要澄清
[Nitpick]: 小问题,可选修复
8.3 代码审查工具集成
# ===== SonarQube 代码质量门禁 =====
路径:项目设置 → Quality Gates
质量门禁条件:
- Bugs: 0
- Vulnerabilities: 0
- Security Hotspots: 0
- Code Smells: < 50
- Coverage: > 80%
- Duplicated Lines: < 3%
- Technical Debt Ratio: < 5%
# ===== Jenkins Pipeline 集成代码审查 =====
pipeline {
agent any
stages {
stage('Code Review Checks') {
parallel {
stage('SonarQube Analysis') {
steps {
withSonarQubeEnv('sonarqube-prod') {
sh 'mvn sonar:sonar'
}
}
}
stage('Unit Tests') {
steps {
sh 'mvn test'
}
post {
always {
junit 'target/surefire-reports/*.xml'
}
}
}
stage('Security Scan') {
steps {
sh 'mvn dependency-check:check'
}
}
}
}
stage('Quality Gate') {
steps {
timeout(time: 1, unit: 'HOURS') {
waitForQualityGate abortPipeline: true
}
}
}
}
}
9. Git Hooks 自动化
9.1 Husky + lint-staged 配置
# ===== Node.js 项目配置示例 =====
# 1. 安装依赖
npm install --save-dev husky lint-staged eslint prettier
# 2. 初始化 Husky
npx husky install
npx husky add .husky/pre-commit "npx lint-staged"
npx husky add .husky/commit-msg "npx --no -- commitlint -E HUSKY_GIT_PARAMS"
# 3. 配置 package.json
cat >> package.json << 'EOF'
{
"scripts": {
"prepare": "husky install",
"lint": "eslint src/",
"format": "prettier --write src/"
},
"lint-staged": {
"*.{js,jsx,ts,tsx}": [
"eslint --fix",
"prettier --write"
],
"*.{json,md}": [
"prettier --write"
]
},
"commitlint": {
"extends": ["@commitlint/config-conventional"]
}
}
EOF
# 4. 配置 ESLint (.eslintrc.js)
cat > .eslintrc.js << 'EOF'
module.exports = {
env: {
browser: true,
es2021: true,
node: true,
},
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
],
parser: '@typescript-eslint/parser',
plugins: ['@typescript-eslint'],
rules: {
'no-console': 'warn',
'eqeqeq': ['error', 'always'],
'curly': ['error', 'all'],
},
};
EOF
# 5. 配置 Prettier (.prettierrc)
cat > .prettierrc << 'EOF'
{
"semi": true,
"singleQuote": true,
"tabWidth": 2,
"trailingComma": "es5",
"printWidth": 100
}
EOF
9.2 自定义 Git Hooks 脚本
#!/bin/bash
# .git/hooks/pre-commit - 提交前检查脚本
echo "Running pre-commit checks..."
# 1. 检查是否有敏感信息
if git diff --cached | grep -iE "(password|secret|api_key|token)\s*[=:]\s*['\"][^'\"]+['\"]"; then
echo "❌ Error: Potential secrets detected in commit!"
exit 1
fi
# 2. 检查大文件
MAX_SIZE=10485760 # 10MB
for file in $(git diff --cached --name-only); do
if [ -f "$file" ]; then
size=$(stat -f%z "$file" 2>/dev/null || stat -c%s "$file" 2>/dev/null)
if [ "$size" -gt $MAX_SIZE ]; then
echo "❌ Error: File $file exceeds 10MB limit ($size bytes)"
exit 1
fi
fi
done
# 3. 检查提交信息格式
COMMIT_MSG_FILE=$1
COMMIT_MSG=$(cat $COMMIT_MSG_FILE)
if ! echo "$COMMIT_MSG" | grep -qE "^(feat|fix|docs|style|refactor|test|chore)\(.+\): .+"; then
echo "❌ Error: Commit message does not follow convention!"
echo "Expected format: type(scope): description"
echo "Example: feat(auth): add JWT token authentication"
exit 1
fi
echo "✅ All pre-commit checks passed!"
exit 0
10. 团队协作规范
10.1 提交信息规范(Conventional Commits)
# ===== 提交信息格式 =====
():
type 类型说明:
feat: 新功能
fix: Bug 修复
docs: 文档更新
style: 代码样式(不影响代码含义的变动)
refactor: 代码重构(既不是新功能也不是 Bug 修复)
perf: 性能优化
test: 测试用例
chore: 构建过程或辅助工具变动
revert: 回退提交
merge: 合并分支
scope 影响范围:
auth: 认证授权模块
user: 用户模块
order: 订单模块
payment: 支付模块
api: 接口层
db: 数据库相关
ui: 前端界面
config: 配置文件
subject 简短描述:
- 使用祈使句、现在时态
- 首字母不大写
- 末尾不加句号
- 长度不超过 50 字符
# ===== 完整提交示例 =====
feat(auth): add JWT token authentication
Body(可选,详细说明):
- Implement JWT-based stateless authentication
- Add token refresh mechanism
- Configure token expiration time
Footer(可选,关联 Issue):
Closes #123
BREAKING CHANGE: Requires updating client-side auth logic
10.2 分支命名规范
# ===== 分支命名规则 =====
feature/ 功能分支:
feature/user-login
feature/shopping-cart
feature/payment-integration
feature/JIRA-123-user-profile # 关联 JIRA 任务号
bugfix/ Bug 修复分支(也可用 fix/):
bugfix/login-timeout-issue
fix/memory-leak-in-cache
bugfix/JIRA-456-null-pointer
release/ 发布分支:
release/1.0.0
release/2024-q1
release/v1.2.3
hotfix/ 紧急修复分支:
hotfix/security-patch
hotfix/production-crash-fix
hotfix/1.0.1
experiment/ 实验性分支(也可用 exp/):
experiment/new-ui-design
exp/performance-test
wip/ 进行中分支(Work In Progress):
wip/refactor-database-layer
# ===== 分支生命周期管理 =====
短期分支(feature/bugfix): < 2 周
- 开发完成后立即合并
- 合并后及时删除
中期分支(release): 1-4 周
- 发布完成后合并到 main 和 develop
- 保留历史记录但不活跃开发
长期分支(main/develop): 永久
- 作为集成分支持续维护
- 定期清理已合并的旧分支
10.3 团队开发最佳实践
✅ 每日开发流程:
- 晨会前:拉取最新 develop 分支,解决本地冲突
- 开发中:小步提交,每 2-3 小时 commit 一次
- 提交前:运行本地测试,确保代码质量
- 下班前:推送代码到远程,创建/更新 MR/PR
- 每周五:清理已合并的本地分支