For my first blog post here, I'll address something that's come up a few times during my time as a student at General Assembly's software engineering program: merging branches with unrelated histories.
When I have to merge unrelated histories, it's usually because I need to push to a remote repo that already has some content. A good use case is when you have made a new GitHub repo with a readme, but now you need to push a totally different local repo to this GitHub repo. These repositories are not related to each other and can't be merged using the default settings.
Let's walk through how to merge unrelated histories!
Fetching a remote repository
When you need to sync local and remote repositories, you'll have to add the remote repo as a remote
of your local one. You can do this using the command git remote add <remote name> <remote url>
. You can fill in whatever name you like for the name of your new remote. For this exercise, I called my remote part3
.
Then, you'll have to fetch this repository using git fetch part3
.
The hard part: merging
Unlike when dealing with related branches, when you try git merge part3/master
with two unrelated branches, Git won't be able to merge these branches. Instead, Git offers a "fatal" message that seems designed to give users horrible nightmares.
What this means is that Git is not able to tell how the files in these two repos should relate to each other, and cannot perform a conventional merge.
But this doesn't mean that Git cannot perform any merge. In fact, all you need to do to merge unrelated branches is to use the flag --allow-unrelated-histories
. This tells Git to combine all the files and commits of both unrelated branches into one branch, as long as there are no file conflicts.
When there are file conflicts, you'll have to use the normal Git workflow to resolve them.
File conflicts
During my exercise, I had one conflict: README.md existed in both repositories, and it was not possible for Git to automatically merge the content of each file. In my situation, I needed only the remote README.md, so I used Visual Studio Code's user-friendly merge conflict tool to resolve the conflicts.
Commit and push
After fixing the merge conflicts, all you have to do to resolve the unrelated histories is commit. Then push and... voila! Your content from both repositories is now integrated into one GitHub repo.
Now you have one less thing to worry about when using Git. Use the --allow-unrelated-histories
flag the next time you find yourself needing to merge two unrelated branches.
Top comments (1)
if we need to change the branch, how we do this in this case?