GitHub’s Branch Protection Rules are the gatekeepers that ensure code quality and stability before changes hit your main branches.
Let’s see this in action. Imagine a repository with a main branch. To protect it, we navigate to Settings -> Branches -> Add branch protection rule. We’ll enter main as the branch name pattern.
Now, the crucial part: Require a pull request before merging. Check this box. This is the core of code reviews. It means no direct pushes to main; all changes must come through a pull request.
Next, Require approvals. This is where you enforce the review process. Set it to 1 or 2 (or more, depending on your team’s policy). This ensures at least one (or two) pair of eyes has vetted the code.
You can also add Require status checks to pass before merging. This is vital. It means that automated checks like CI builds, linting, and tests must succeed before a reviewer can even approve, let alone merge. You’ll need to have these configured in your CI system (like GitHub Actions, Jenkins, etc.) and then select them here. For example, if you have a GitHub Actions workflow named build-and-test, you’d type build-and-test into the "Search status checks" field.
Consider a scenario where a developer, Alice, wants to merge a feature into main. She pushes her feature branch, creates a pull request, and assigns Bob as a reviewer. If Bob approves, and all status checks pass, Alice can then merge. If Bob requests changes, Alice must address them and push updates to her branch. The pull request will then prompt Bob for another review.
The surprising part is how granularly you can control this. You can require reviews from specific teams or individuals, not just anyone. Under the Require approvals section, there’s an option Dismiss stale pull request approvals when new commits are pushed. This is a game-changer for ensuring reviewers are always looking at the latest version of the code. If Alice pushes new commits after Bob has already approved, Bob’s approval is dismissed, forcing him to re-evaluate the updated code.
You can also enforce that the person merging the pull request is not the author of the changes. This is done by checking Restrict who can push to matching branches and then adding users or teams who are allowed to merge, ensuring it’s not the developer themselves closing the loop.
The true power lies in combining these rules. You can have a rule like: Require 2 approvals, Require status checks to pass (build-and-test, linting), and Dismiss stale approvals. This creates a robust pipeline: code is written, automated checks run, a human reviews the code and the results of the automated checks, and then the code is merged.
The next hurdle you’ll likely face is managing merge conflicts when multiple people are working on the same code, as the branch protection rules will prevent you from simply overwriting changes.