How to Handle Protected Branches in Git: A Step-by-Step Guide
When you encounter the error message "remote: Branch refs/heads/master can only be modified through pull requests," it indicates that the master branch in your repository is protected. This protection is usually enforced by pre-receive hooks on the remote repository, preventing direct pushes to maintain code quality and enforce code reviews.
To resolve this issue, you should create a new branch for your changes and then create a pull request (PR) to merge those changes into the master branch. Here’s a detailed guide to help you through the process:
Step-by-Step Guide
1. Create a New Branch
First, create a new branch from master. This new branch will hold your changes until they are reviewed and merged.
git checkout -b my-feature-branch
2. Make Changes
Commit your changes to this new branch. Ensure your commit messages are descriptive to help reviewers understand the changes.
git add .
git commit -m "Your commit message"
3. Push the New Branch
Push your new branch to the remote repository. This makes your changes available for review.
git push origin my-feature-branch
4. Create a Pull Request
Go to your repository on Bitbucket (or the relevant remote repository hosting service), and create a pull request to merge my-feature-branch into master. This step involves the web interface where you describe your changes, the purpose of the pull request, and assign reviewers.
5. Review and Merge
Have your team review the pull request. Once it is approved, merge the pull request into the master branch through the web interface. This ensures that all changes are reviewed before being integrated into the main codebase.
Summary of Commands
Here's a quick reference for the commands you need to execute:
Step 1: Create a new branch
git checkout -b my-feature-branch
Step 2: Add and commit your changes
git add .
git commit -m "Your commit message"
Step 3: Push the new branch
git push origin my-feature-branch
Step 4: Create a pull request
(This step is done through the web interface)
By following these steps, you adhere to the repository’s policy of modifying the master branch only through pull requests. This practice ensures code quality and maintainability by enforcing code reviews before changes are merged into the main branch. Happy coding!
Imported from rifaterdemsahin.com · 2025