0
0
Gitdevops~5 mins

Branch protection rules in Git - Commands & Configuration

Choose your learning style9 modes available
Introduction
Branch protection rules help keep important branches safe by preventing accidental changes. They stop direct pushes or deletions and require reviews before changes are added.
When you want to stop team members from accidentally deleting the main branch.
When you want to make sure every change to the main branch is reviewed by someone else.
When you want to prevent force pushes that could overwrite history on important branches.
When you want to require passing tests before merging code into a shared branch.
When you want to keep release branches stable and controlled.
Commands
Rename the current branch to 'main' to use a standard protected branch name.
Terminal
git branch -m main
Expected OutputExpected
No output (command runs silently)
Push the 'main' branch to the remote repository and set it as the default upstream branch.
Terminal
git push -u origin main
Expected OutputExpected
Enumerating objects: 5, done. Counting objects: 100% (5/5), done. Delta compression using up to 8 threads Compressing objects: 100% (3/3), done. Writing objects: 100% (5/5), 450 bytes | 450.00 KiB/s, done. Total 5 (delta 0), reused 0 (delta 0), pack-reused 0 To https://github.com/username/repository.git * [new branch] main -> main Branch 'main' set up to track remote branch 'main' from 'origin'.
-u - Sets upstream tracking for the branch
Delete a feature branch from the remote repository to keep branches clean after merging.
Terminal
git push origin --delete feature-branch
Expected OutputExpected
To https://github.com/username/repository.git - [deleted] feature-branch
--delete - Deletes the specified remote branch
Mark the local repository directory as safe to avoid permission errors when running Git commands.
Terminal
git config --global --add safe.directory /home/user/myrepo
Expected OutputExpected
No output (command runs silently)
--global - Apply config globally for the user
Key Concept

If you remember nothing else from branch protection, remember: protect important branches by requiring reviews and blocking direct pushes.

Common Mistakes
Trying to enforce branch protection only with local Git commands.
Branch protection rules are set on the remote repository platform (like GitHub), not locally.
Use the repository hosting service's settings to configure branch protection rules.
Pushing directly to the main branch without a pull request when protection is enabled.
Protected branches block direct pushes to prevent unreviewed changes.
Create a feature branch, make changes, then open a pull request for review before merging.
Summary
Rename your main branch to a standard name like 'main' for easier protection.
Push branches to the remote repository and set upstream tracking.
Delete remote branches after merging to keep the repository clean.
Branch protection rules must be set on the remote platform, not locally.