How To Merge Unrelated Git Histories With Conflicts
I recently took over a project that was hosted on WP Engine. When I took over the project I didn’t have a git repository for it. I could have pulled from WP Engine initially – but I didn’t. I downloaded from a WP Engine backup instead and committed this to my new git repository. This was the start of my problem.
The code base was largely the same but git sees them as two separate repositories now. I continue on not knowing I’ll have a problem and work on the features and enhancements I’ve been tasked with building. I set up a staging environment and push to that with no issue. All the work gets approved on staging and its time to push to production. Now I’m aware of the problem.
The problem looks something like this
Now the problem is I can’t just do a force push. I’ve got to handle the merge somewhat elegantly.
Allow me to show you the command that ended up allow me to solve this issue and explain how it works.
I need to warn you that this is a risky maneuver so if you attempt this, please make sure you understand the consequences.
How to Do It
How to merge unrelated histories with merge conflicts in Git
Start from the right branch
Make sure the current branch is the branch where you want to merge the feature branch to (master/main)
Run the command
git merge feature/landing-page –allow-unrelated-histories -s recursive -X theirs
Handle remaining conflicts
There still might be outstanding conflicts that you will need to manually resolve
What Does the Command Do?
git merge feature/landing-page --allow-unrelated-histories -s recursive -X theirs
Command | Meaning |
---|---|
git | We tell the command line we want to use git |
merge | Tells git we want to merge a different branch into the branch we are currently on |
feature/landing-page | The branch we are merging in to our current branch |
–allow-unrelated-histories | Stops git from cancelling the merge due to unrelated histories |
-s | Adds a signoff message to the commit – helpful since this a dangerous command to run |
recursive | The default merge strategy when pulling or merging one branch but it doesn’t hurt to include it |
-X theirs | The bit that says if there is a merge conflict we want to favor the branch we are merging in over the branch we are currently on |
Results
The above allowed me to
Merge the unrelated histories into one
Accept the incoming changes as the desired changes by default when there are merge conflicts (this saved from me having to correct thousands of files of code in a merge conflict resolution)
There were still some files where I had to manually review the merge conflict and make a decision but it was a total of 11 files as opposed to more than 1000 files with merge conflicts.