Video in progress

Strong Middle 🌿 Git

How do you protect the `main` branch? How do branch protection, required checks and CODEOWNERS work together?

Branch protection closes direct pushes and force pushes and requires a PR, an approval and green CI for merging. CODEOWNERS defines who must review which folder. Together they move the rule from people's memory to the server.

📖 Answer

Typical settings on GitHub (GitLab's "protected branches" and "approval rules" work the same way):

  • pushing directly is closed, and force push and deletion are forbidden;
  • at least 1-2 approvals; when a new commit arrives, old approvals are dismissed (stale review dismissal);
  • required status checks: build, test, sonar, dependency-scan;
  • "branch must be up to date": the PR must have been tested against the very latest main. In a repository with many PRs this creates a queue, which is why a merge queue is used;
  • no exceptions even for admins: "include administrators".

CODEOWNERS:

# .github/CODEOWNERS
*                              @company/backend
/src/main/resources/db/migration/ @company/dba
/src/main/java/uz/app/payment/    @company/payments-team
/.github/workflows/               @company/platform

With "Require review from Code Owners" turned on, a PR that touches a migration cannot be merged without the DBA's approval.

From practical experience: if you rename a required check in CI, all PRs get stuck in a "pending" state, so update the protection rule at the same time. And in CODEOWNERS, list a team, not one person: a single person on vacation can halt the whole repository.