Protect main and work through pull requests
In this task you'll make main accept changes only through reviewed pull requests.
A pull request (PR) asks to merge a branch into main. It shows the diff, runs the pipeline's checks and collects reviews before anything changes.
Branch protection (or a ruleset) makes this the only way in: no direct pushes to main, at least one approval, and checks that must pass.
Example. At Fernhill Cloud, main is protected: every change needs one approval and a green build. When a junior's PR committed a password, the reviewer caught it before it reached main.
Before you start
You need: A free GitHub account. Time: 20 minutes.
Where to look
- GitHub
- Repository
- Settings
- Rules
- Rulesets
- New branch ruleset
Steps
- Create a repository on GitHub and push the shop folder to it (GitHub shows the commands after you create it).
- Open Settings, then Rules, then Rulesets, and select New branch ruleset. Target the default branch.On older screens: Branches, then Add branch protection rule.
- Tick Require a pull request before merging with 1 approval, and Block force pushes. Set enforcement to Active and save.Private repositories on the free plan may not enforce rulesets: use a public practice repository.
- Make a branch, push it, and open a PR. Read the Files changed tab, then merge it.
Commands
# Push a branch and open a pull request from the command line (GitHub CLI)
git switch -c feature/banner
git commit -am "Add sale banner"
git push -u origin feature/banner
gh pr create --fill
Watch out for
- Cost
- Free for public repositories.
- Security
- Without protection, anyone with write access can push straight to production code.
- Common mistakes
- Approving your own PRs by giving yourself admin bypass, or making checks required before they exist (nothing can merge).
Clean up
Keep the repository for the CI tasks, or delete it from Settings (GitHub asks you to confirm by email).
Words to know
- Pull request
- A request to merge one branch into another, with review and checks.
- Ruleset
- GitHub's newer way to protect branches: who can push, which checks must pass, how many approvals.
- Required check
- A pipeline job that must succeed before merging.
Tick off each step and track your progress in the guide.
Open this task in DevOps, Hands On