分支保护规则
分支保护规则限制对重要分支的直接操作,确保代码变更经过审核。
什么是分支保护
分支保护设置后:
- 不能直接推送
- 不能强制推送
- 不能删除分支
- 必须通过 PR 合并
- 必须通过审核
保护的分支
| 分支 | 重要性 | 保护级别 |
|---|---|---|
| main/master | 生产环境 | 最高保护 |
| release/* | 发布分支 | 高保护 |
| develop | 开发主干 | 中保护 |
GitHub 设置分支保护
Bash
Settings → Branches → Add branch protection rule
Rule name: main
保护规则选项
| 选项 | 说明 |
|---|---|
| Require a pull request before merging | 必须通过 PR 合并 |
| Require approvals | 需要审核批准 |
| Require review from Code Owners | 需要代码负责人审核 |
| Dismiss stale pull request approvals | 新提交时清除旧审核 |
| Require status checks to pass before merging | 必须通过 CI 检查 |
| Require branches to be up to date | 分支必须是最新的 |
| Require conversation resolution | 必须解决所有讨论 |
| Require signed commits | 提交必须签名 |
| Include administrators | 管理员也遵守规则 |
| Restrict who can push | 限制推送权限 |
| Allow force pushes | 允许强制推送(通常禁用) |
| Allow deletions | 允许删除(通常禁用) |
常用保护配置
YAML
main 分支保护建议:
✅ Require a pull request before merging
✅ Require approvals: 1-2
✅ Dismiss stale pull request approvals
✅ Require status checks to pass
✅ Required checks: lint, test, build
✅ Require conversation resolution
✅ Do not allow bypassing the above settings
❌ Allow force pushes
❌ Allow deletions
保护后的操作流程
text
正常流程:
1. 创建功能分支
2. 开发并推送
3. 创建 PR
4. 通过 CI 检查
5. 通过审核
6. 合入保护分支
禁止操作:
git push origin main # 被拒绝
git push -f origin main # 被拒绝
git branch -D main # 被拒绝
审核要求配置
text
Require approvals: 2
# 需要 2 人审核批准才能合并
Require review from Code Owners
# CODEOWNERS 文件定义的负责人必须审核
CODEOWNERS 文件
text
# .github/CODEOWNERS 文件
# 定义各目录的代码负责人
# 全局
* @team-admin
# 按目录
/src/api/ @api-team @api-lead
/src/ui/ @ui-team
/docs/ @docs-team
# 按文件类型
*.go @go-team
*.md @docs-team
CI 检查要求
text
# Required status checks
# GitHub Actions 检查名称必须匹配
jobs:
lint:
name: lint # PR 要求填写这个名称
test:
name: test # PR 要求填写这个名称
管理员豁免
text
默认:管理员可以绕过保护规则
建议:
✅ Include administrators
管理员也遵守规则,避免意外
例外:
紧急情况下可以临时关闭保护
合并后立即恢复
分支保护效果
text
无保护:
main: 直接推送 → 可能误操作 → 代码损坏
有保护:
main: PR → 审核 → CI → 合并 → 安全可靠
分支保护是代码安全的最后一道防线,重要分支必须保护。
要点总结
- main/release 分支必须保护
- 要求 PR + 审核 + CI 检查
- 禁止强制推送和删除
- CODEOWNERS 定义代码负责人
- 管理员也应遵守保护规则
📝 发现内容有误?点击此处直接编辑