Branch_Protection_Rules
Branch Protection Rules
Protect important branches with rules.
π Overview
graph LR
A[Protected Branch] --> B[Require PR]
A --> C[Require Reviews]
A --> D[Require CI Pass]
A --> E[Block Force Push]
βοΈ Configure via Web
- Go to repo Settings
- Click "Branches"
- Add rule for branch pattern
π§ Configure via CLI
Create Rule
gh api repos/{owner}/{repo}/branches/{branch}/protection -X PUT \
-H "Accept: application/vnd.github.v3+json" \
-f required_status_checks='{"strict":true,"contexts":["ci/test"]}' \
-f enforce_admins=true \
-f required_pull_request_reviews='{"dismiss_stale_reviews":true,"require_code_owner_reviews":true}'
Creates branch protection via API.
View Protection
gh api repos/{owner}/{repo}/branches/{branch}/protection
Shows current protection settings.
Delete Protection
gh api repos/{owner}/{repo}/branches/{branch}/protection -X DELETE
Removes branch protection.
π Common Rules
Require Pull Request
- No direct pushes
- Changes must go through PR
Require Approvals
gh api repos/{owner}/{repo}/branches/main/protection \
-f required_pull_request_reviews='{"required_approving_review_count":2}'
Requires 2 approving reviews.
Require Status Checks
gh api repos/{owner}/{repo}/branches/main/protection \
-f required_status_checks='{"strict":true,"contexts":["ci/test","ci/lint"]}'
Requires CI checks to pass.
Require Up-to-date Branch
The strict: true setting requires branch to be up to date before merging.
Block Force Push
Enabled by default with protection.
Require Signed Commits
gh api repos/{owner}/{repo}/branches/main/protection/required_signatures -X POST
Requires GPG signed commits.
π CODEOWNERS
Create .github/CODEOWNERS:
# Default owners
* @default-team
# Specific paths
/src/ @frontend-team
/api/ @backend-team
*.js @js-experts
Automatically requests reviews from code owners.
π‘ Tips
Pattern Matching
Use * for all branches, release/* for release branches.
Admin Override
Decide if admins can bypass rules.
π Related
#github #protection #rules #branches