Branch protection with required checks
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Most pull requests are green, until the day someone merges a red one or pushes straight to main. How do you turn "no green, no merge" from a promise into a rule that GitHub enforces for you?
Rulesets: require a pull request and passing checks
A ruleset is a set of rules that GitHub enforces on branches, such as "changes only through a pull request" and "these checks must pass". You create it under Settings → Rules → Rulesets.
This JSON is a ruleset for main. You can import it in GitHub, or tick the same options by hand with the steps below.
- Open the repository's Settings → Rules → Rulesets → New ruleset → New branch ruleset.
- Name it
Protect main, set Enforcement to Active, and add the targetInclude default branch. - Tick Restrict deletions and Block force pushes.
- Tick Require a pull request before merging, with 1 required approval.
- Tick Require status checks to pass, add the check
build-testand tick Require branches to be up to date. - Save, then open a test pull request and check that Merge is blocked until CI is green.
Example 1 · The ruleset as JSON (export and import)
Runs in: GitHub: Settings → Rules → Rulesets → Import a ruleset
{ "name": "Protect main", "target": "branch", "enforcement": "active", "conditions": { "ref_name": { "include": ["~DEFAULT_BRANCH"], "exclude": [] } }, "bypass_actors": [], "rules": [ { "type": "deletion" }, { "type": "non_fast_forward" }, { "type": "pull_request", "parameters": { "required_approving_review_count": 1, "dismiss_stale_reviews_on_push": true, "require_code_owner_review": false, "require_last_push_approval": false, "required_review_thread_resolution": true } }, { "type": "required_status_checks", "parameters": { "strict_required_status_checks_policy": true, "required_status_checks": [ { "context": "build-test" } ] } } ]}Ruleset "Protect main" created (Active, targets: Default branch) Restrict deletions Block force pushes Require a pull request before merging (1 approval, dismiss stale approvals) Require status checks to pass: build-test (branches must be up to date)
What this code does
non_fast_forwardis the force-push block,strict_required_status_checks_policyis "branches must be up to date", andcontextis the check name your job reports.- Keeping the ruleset as JSON in your notes or repository lets you apply the same protection to the next project in one import.
The older branch protection rules (Settings → Branches) do the same job; new repositories should prefer rulesets, which can be exported and imported as JSON.
Two rules matter most for main. Require a pull request before merging: nobody, not even you, pushes straight to main. Require status checks to pass: the pull request can be merged only when the chosen CI jobs report success. Protection rules on private repositories need a paid GitHub plan; on public repositories they are free.
Predict the output
What does this rule do?
Read the rule from the ruleset, then pick the effect.
Round 1 of 3
What does this rule block?
Which checks to require, and the renaming trap
A required status check is a CI result, identified by the job's name, that must be successful on a pull request's latest commit before GitHub allows the merge.
This program decides whether a pull request can merge. After a job is renamed, the required name never arrives.
Example 2 · Why a renamed job blocks every pull request
import java.util.Map;import java.util.Set;
public class RequiredChecksDemo { static String mergeState(Set<String> required, Map<String, String> reported) { for (String check : required) { String result = reported.get(check); if (result == null) { return "blocked: " + check + " expected, waiting for status to be reported"; } if (!result.equals("success")) { return "blocked: " + check + " is " + result; } } return "mergeable"; }
public static void main(String[] args) { Set<String> required = Set.of("build-test");
System.out.println("PR 41: " + mergeState(required, Map.of("build-test", "success"))); System.out.println("PR 42: " + mergeState(required, Map.of("build-test", "failure"))); // ci.yml renamed the job to "tests"; the ruleset still asks for "build-test" System.out.println("PR 43: " + mergeState(required, Map.of("tests", "success"))); }}PR 41: mergeable PR 42: blocked: build-test is failure PR 43: blocked: build-test expected, waiting for status to be reported
What this code does
- PR 42 is blocked as intended: its tests failed. PR 43's tests passed, but under the new name
tests, so the requiredbuild-testnever arrives and GitHub keeps waiting. - The fix for PR 43 is in the settings, not the code: change the required check to
testsin the same change that renames the job.
A job's check name is its name: or, without one, the job id, such as build-test. A matrix reports one check per value: build-test (21) and build-test (25). Require the checks that prove a change is safe to merge, the build and tests. Do not require jobs that run only on main, such as image; they never run on a pull request, so the rule could never be met.
The trap: the rule stores the name. Rename the job in ci.yml and the old name never reports again, so no pull request can be merged. When you rename a job, update the ruleset in the same change.
Fix the error
Unblock the pull requests
The job id in ci.yml is now tests. Choose the line that replaces the old one.
Every new pull request waits forever. Which line replaces line 3?
Error
Expected — Waiting for status to be reported
Up to date, no force pushes, review
Require branches to be up to date means a pull request must contain the latest main before it can be merged, so CI tests the combined code, not the old one.
Two pull requests can each pass alone and still break main together. This program shows how.
Example 3 · Up to date or not: two green PRs that break main together
import java.util.HashSet;import java.util.Set;
public class UpToDateDemo { // main has a method price(); each PR was tested against the old main static boolean compiles(Set<String> methodsDefined, Set<String> methodsCalled) { return methodsDefined.containsAll(methodsCalled); }
public static void main(String[] args) { Set<String> mainDefines = new HashSet<>(Set.of("price"));
// PR A renames price() to unitPrice() and updates every caller it knows about Set<String> afterA = new HashSet<>(Set.of("unitPrice")); // PR B adds a new caller of price(), tested against the old main Set<String> callsInB = Set.of("price");
System.out.println("PR B alone on old main : " + (compiles(mainDefines, callsInB) ? "green" : "red")); System.out.println("main after A, then B : " + (compiles(afterA, callsInB) ? "green" : "red")); System.out.println("with 'up to date' rule : PR B must merge main first and goes red before merging"); }}PR B alone on old main : green main after A, then B : red with 'up to date' rule : PR B must merge main first and goes red before merging
What this code does
- Each pull request was green against the
mainit started from. Merged one after the other, B calls a method that A removed, somainno longer compiles. - "Require branches to be up to date" makes B pull in A's change first; CI then runs on the combined code and catches the problem before the merge.
Two more rules close the remaining gaps:
- Block force pushes: nobody can rewrite
main's history withgit push --force, which could delete merged work. - Require approvals: at least one other person reviews the code. On a solo project you can leave this at zero, but keep the checks required.
Administrators can bypass rules only if you add them to the bypass list; leave it empty for main.
The everyday flow
The pull request flow is the path every change takes to main: feature branch, pull request, CI green, review, then merge. ShopLite uses a squash merge, which turns the branch into one tidy commit.
These commands take one change from a feature branch to a squash merge, with CI and a review in between.
Example 4 · The flow from the terminal
Runs in: the shoplite-api repository with the GitHub CLI (gh) logged in
git switch main && git pullgit switch -c feature/coupon-expiry# ... edit, test locally with ./mvnw verify, commit ...git push -u origin feature/coupon-expirygh pr create --base main --title "Reject expired coupons" --body "Adds expiry check + tests"gh pr checks --watch # wait for CIgh pr merge --squash --delete-branchCreating pull request for feature/coupon-expiry into main in asha-rao/shoplite-api https://github.com/asha-rao/shoplite-api/pull/44 $ gh pr checks --watch All checks were successful 0 cancelled, 0 failing, 1 successful, 0 skipped, and 0 pending checks ✓ CI/build-test (pull_request) 4m12s https://github.com/asha-rao/shoplite-api/actions/runs/... $ gh pr merge --squash --delete-branch X Pull request asha-rao/shoplite-api#44 is not mergeable: the base branch policy prohibits the merge. (after Ravi approves the PR) ✓ Squashed and merged pull request asha-rao/shoplite-api#44 (Reject expired coupons) ✓ Deleted local branch feature/coupon-expiry and switched to branch main
What this code does
- CI was green, but the first merge attempt was refused: the ruleset also requires one approval. After the review, the squash merge goes through.
- The merge is a push to
main, so the workflow runs again there and, this time, the image job builds and pushessha-...for the merged commit.
The merge to main triggers the push workflow, which builds and pushes the image.
If CI goes red, fix it on the same branch and push again; the checks run again on the new commit. If main moved on, update the branch, and the checks run again on the merged result.
Order of execution
Order the flow
Tap the steps in the order a change travels.
A status badge in the README
A status badge is a small image that shows whether a workflow's latest run on the default branch passed. GitHub serves it at a fixed URL for every workflow.
Put the Markdown below at the top of README.md. The image shows the latest result, and a click opens the workflow's runs.
# ShopLite API[](https://github.com/asha-rao/shoplite-api/actions/workflows/ci.yml)Recruiters and teammates see at a glance that the project builds and its tests pass.
You can also copy the Markdown from the workflow page: Actions → CI → the "..." menu → Create status badge.
Next step
Check your understanding
11 quick questions