Some time ago, I worked on a project that was split into multiple Git repositories. After a few weeks we decided, that it wasn’t longer necessary to have multiple repositories for this project, so we decided to merge them. The question was, if it is possible to merge multiple code bases without losing their history. The answer is yes. We have two ways on how to tackle this. The first way uses one of the repositories as the new main repository. The second option is to create a new repository for that purpose. We chose option one, because we already had a repository that acted as the main repository. If you choose to create a new repository, you can still follow the steps below. The only difference is, that you need at least one commit on that new repository, to be able to merge into it.
Before merging our repositories, we might first have to do some preparation on them. To prevent merge conflicts, you could move all files into a new directory, before merging them.
# Create a new directory
# Move all files into repo1
mv * repo1
# Commit those changes
git commit -am "Prepare for repository merge"
# Push changes to origin
When thats done, add the repository as a remote on the new main repository.
git remote add repo1 firstname.lastname@example.org:project/repo1.git
After that the merge is quite simple. We just have to append
--allow-unrelated-histories to allow the merge of unrelated code bases.
git merge repo1/master --allow-unrelated-histories
If thats successful, the merge is done.
Redo the steps above for every repository you want to merge.