Master Branch and 'Origin/master' Have Diverged, How to 'Undiverge' Branches'?
When the master branch and origin/master have diverged, it means that both your local master branch and the remote origin/master branch have separate changes that are not shared with each other. To resolve this divergence and synchronize them, you have a few options depending on the situation. Here’s a step-by-step guide to handle this:
Understanding the Divergence
- Local Divergence: Your local
masterbranch has commits that are not onorigin/master. - Remote Divergence: The
origin/masterbranch has commits that are not on your localmaster.
Resolving Divergence
1. Rebase Your Local Branch on Top of origin/master
If you want to keep your local changes but apply them on top of the latest origin/master, follow these steps:
Fetch Latest Changes from Remote
First, update your local repository with the latest changes from the remote:
Rebase Your Local Branch
Rebase your local
masterbranch on top oforigin/master:
Resolve Conflicts (if any)
If there are conflicts during the rebase, Git will pause and prompt you to resolve them. Resolve conflicts in the files, then:
If you want to abort the rebase at any time, you can use:
Push the Rebased Branch
After a successful rebase, you may need to force push your changes to the remote branch because rebase rewrites commit history:
Note: Be cautious with
--force, as it will overwrite the remote branch history. Use--force-with-leasefor a safer approach:
2. Merge origin/master into Your Local Branch
If you prefer to merge origin/master into your local master, follow these steps:
Fetch Latest Changes from Remote
Update your local repository:
Merge
origin/masterinto Your Local BranchMerge the remote changes into your local
master:
Resolve Conflicts (if any)
If there are conflicts during the merge, resolve them in the affected files. After resolving conflicts:
This completes the merge process.
Push the Merged Branch
Push the merged changes to the remote repository:
Choosing Between Rebase and Merge
- Rebase: Rebase is preferred if you want to maintain a linear project history without merge commits. It rewrites commit history, so be cautious when using it on shared branches.
- Merge: Merge is preferred if you want to preserve the complete history of changes and are okay with merge commits. It combines changes without rewriting history.
Example Workflow for Rebase
Fetch Latest Changes:
Rebase Local Branch:
Resolve Conflicts (if any):
Push with Force:
Example Workflow for Merge
Fetch Latest Changes:
Merge Remote Changes:
Resolve Conflicts (if any):
Push Changes:
Summary
To resolve divergence between your local master and origin/master:
- Rebase: Reapply your local commits on top of the remote branch using
git rebase origin/master, then force push if necessary. - Merge: Merge the remote branch into your local branch using
git merge origin/master, then push the result.
Choose the method that best fits your workflow and project requirements.