Branch Protection and Policies
What you'll learn: How to lock down critical branches so no one can merge untested or unreviewed code straight into production.
Why Branch Protection Matters
In team environments, your main or production branch is sacred—it's the code that runs in production, that customers see, that must stay stable. Without protection, anyone could push broken code directly or merge a feature branch before it's ready. Branch protection enforces rules before changes can be merged, acting like a quality gate.
Core Protection Rules
Most Git platforms (GitHub, GitLab, Bitbucket) let you configure branch protection policies for specific branches:
- Require pull request reviews: No one merges their own code without at least one (or more) teammate approving it. This enforces the code review workflow you learned earlier.
- Require status checks to pass: Before merging, automated tests (unit tests, linters, security scans) must succeed. If your CI pipeline reports failures, the merge is blocked.
- Enforce linear history: Require rebase or squash merges to keep history clean—no messy merge commits cluttering
main. - Restrict who can push: Only designated maintainers can force-push or bypass rules, preventing accidental overwrites.
The Analogy
Think of branch protection like airport security: you can't board the plane (merge to main) until you've passed the checks (code review, tests). It's a controlled checkpoint, not a free-for-all.
In Practice
On GitHub, navigate to Settings → Branches → Branch protection rules, select main, then check:
- ✅ Require pull request reviews before merging
- ✅ Require status checks (e.g., "CI/tests")
- ✅ Do not allow bypassing the above settings
Now every merge must earn its way in through review and passing tests.
Key Takeaway:
Branch protection policies enforce required reviews, passing tests, and status checks before merging, safeguarding your main branch from untested or unapproved code.