How to protect the master branch in git from merging?

by elise_daugherty , in category: Third Party Scripts , a year ago

How to protect the master branch in git from merging?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by samara , a year ago

@elise_daugherty 

To protect the master branch in Git from accidental merges, you can implement branch protection rules or use branch restrictions. Here's how you can do it:

  1. Create a new branch from your master branch, let's call it "protected-master".
1
git checkout -b protected-master master


  1. Push the protected-master branch to your remote repository.
1
git push origin protected-master


  1. Set up branch protection rules for the master branch in your remote repository (e.g., GitHub, GitLab, Bitbucket). This process varies depending on the hosting platform, but in general, you will have options to configure branch protection rules. Enable branch protection for the master branch. Configure the required checks and review processes for pull requests targeting the master branch. Disable the option to allow direct pushes to the master branch.
  2. Merge changes into the protected-master branch instead of the main master branch.
1
2
git checkout protected-master
git merge <branch-to-merge>


  1. Push the changes to the protected-master branch.
1
git push origin protected-master


Now, any changes made to the master branch will require a pull request and approval process, which will be carried out on the protected-master branch instead. This way, accidental merges to the main master branch can be avoided.