my-notes

Branch_Protection_Rules

1 min read

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

  1. Go to repo Settings
  2. Click "Branches"
  3. 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.



#github #protection #rules #branches

Built with mdgarden