Protecting branches

Topic 3 of 4 in Team workflows8 min readBeginnerFree course

Overview

GitHub flow depends on one promise: main is always deployable. Good intentions aren’t enough to keep it — someone will eventually push straight to main by accident, or force-push over a colleague’s work. Branch rules make the server refuse those pushes, so the workflow is guaranteed rather than hoped for.

Protecting main with rules. A pull request from add-search to main has to pass four gates before it is merged into main: 1 approval (review required), CI passing (status checks), up to date with main, and no force push or deletion. Every gate must pass before the Merge button turns green. Set up in Settings → Rules → Rulesets (or classic branch protection rules). Rules apply to admins too unless you allow a bypass — that is the point.

Rulesets and branch protection

GitHub has two systems:

  • Rulesets (recommended): named sets of rules that target branches (or tags) by name or pattern. Several rulesets can apply to the same branch — they combine, and the most restrictive setting wins. You can disable a ruleset without deleting it, and anyone with read access can see which rules apply.
  • Branch protection rules (classic): one rule per branch pattern. Still supported, and you’ll see them in many existing repositories.

Rulesets for branches and tags are available on public repositories on every plan, and on private repositories with GitHub Pro, Team or Enterprise.

To create one: Settings → Rules → Rulesets → New ruleset → New branch ruleset. Give it a name, set enforcement to Active, add a target such as Include default branch, and choose rules.

The essential rules

For a typical team’s main:

Rule What it prevents
Restrict deletions someone deleting main
Block force pushes rewriting main’s history and losing commits
Require a pull request before merging direct pushes — every change goes through a PR
↳ Required approvals: 1 (or 2) merging without review
↳ Dismiss stale approvals when new commits are pushed approving one version, merging another
↳ Require review from Code Owners changes to sensitive areas without their owners’ review
↳ Require conversation resolution merging with open review comments
Require status checks to pass merging when tests fail — select your CI job (e.g. test)
↳ Require branches to be up to date merging a PR tested against an old main
Require linear history merge commits on main (if your team squashes or rebases)
Require signed commits unverified commits (see Keeping secrets safe)

Start with deletions, force pushes, PR required, one approval and status checks. Add more as the team needs them.

Status checks need a workflow first

A required status check must have run at least once before you can select it — set up the CI workflow (Continuous integration) first, then require its job.

Who do rules apply to?

Everyone — including repository admins — unless they’re on the ruleset’s bypass list. That’s deliberate: the point is that nobody can break main by accident. Keep the bypass list short (perhaps an admin role for emergencies) and use it rarely.

Rulesets as code

The API accepts rulesets as JSON, which lets you apply the same rules to many repositories or keep them under review:

Terminal
gh api --method POST repos/{owner}/{repo}/rulesets --input ruleset.json
gh ruleset list
gh ruleset view
JSON
{
  "name": "Protect main",
  "target": "branch",
  "enforcement": "active",
  "conditions": { "ref_name": { "include": ["~DEFAULT_BRANCH"], "exclude": [] } },
  "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 } }
  ]
}

gh api fills in {owner} and {repo} from the current repository. ~DEFAULT_BRANCH targets whatever the default branch is called. Organisations on GitHub Team or Enterprise can also define rulesets once for many repositories.

Server-side enforcement

Why do these rules work when local Git hooks (chapter 11) can be skipped? Because they’re enforced by the server when it receives a push. Your Git client sends the push; the server checks it against the rules and refuses anything that breaks them:

Text
remote: error: GH013: Repository rule violations found for refs/heads/main.
remote: - Changes must be made through a pull request.
 ! [remote rejected] main -> main (push declined due to repository rule violations)

Plain Git servers have simpler versions of the same idea, which the exercise uses offline: receive.denyNonFastForwards refuses force pushes and receive.denyDeletes refuses deletions. Note that these apply to every branch on the server — they’d also stop people deleting merged feature branches or force-pushing their own branches. To protect only main, a plain Git server needs a pre-receive hook (the capstone project shows one). Self-hosted platforms (GitLab, Gitea, Bitbucket) all offer per-branch protection settings like GitHub’s.

Other useful settings

In Settings → General → Pull Requests:

  • choose which merge methods are allowed (merge commit, squash, rebase),
  • Allow auto-merge, so a PR merges itself once the rules pass (gh pr merge --auto),
  • Automatically delete head branches after merging.

For busy repositories, a merge queue tests each PR combined with those ahead of it before merging, so main never breaks from two PRs that were fine individually but conflict in behaviour.

Protect main on day one. It costs two minutes, and it turns “please don’t push to main” from a request into a guarantee.

Exercise

Enforce the rules on the server

Part 1 (GitHub): write a ruleset JSON for your practice repository that targets the default branch and requires a pull request with one approval, dismisses stale approvals, requires conversations to be resolved and requires a status check called test; it also blocks force pushes and deletion. Apply it with gh api. Part 2 (offline): Git servers can enforce rules too. Configure a local bare repository to refuse non-fast-forward pushes and branch deletions, then prove it: a force-push and a delete must both be rejected while a normal push succeeds.

Terminal
# Part 1 — GitHub ruleset (run inside your practice repo with gh signed in)
# Write ruleset.json, then: gh api --method POST repos/{owner}/{repo}/rulesets --input ruleset.json

# Part 2 — server-side rules on a local "server"
git init -q --bare -b main server.git
git clone -q server.git dev 2>/dev/null && cd dev
echo "v1" > app.txt && git add . && git commit -qm "v1" && git push -qu origin main
cd ..

# 1. Configure server.git to deny force pushes and deletions

# 2. A normal push still works

# 3. A rewritten-history push is rejected, even with --force

# 4. Deleting main on the server is rejected

Summary

  • Branch rules stop mistakes on important branches: no direct pushes, no force pushes, no deletion.
  • Require a pull request with approvals and passing status checks, so every change on main is reviewed and tested.
  • On GitHub, rulesets (Settings → Rules → Rulesets) are the modern way to set these rules; classic branch protection still works.
  • Rules apply to everyone, admins included, unless you add someone to the bypass list.
  • Rules are enforced by the server — clients can’t skip them like they can skip local hooks.