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.

Preparation:
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
mkdir repo1
# Move all files into repo1
mv * repo1
# Commit those changes
git commit -am "Prepare for repository merge"
# Push changes to origin
git push

When thats done, add the repository as a remote on the new main repository.

git remote add repo1 git@git.example.com:project/repo1.git

The merge:
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.

Noah Hilverling
Noah Hilverling
Developer

Nachdem Noah bei einer vierjährigen Exkursion nach Belgien seine Liebe zum Programmieren entdeckte, holte der gebürtige Euskirchener innerhalb kürzester Zeit gleich zwei Schulabschlüsse nach. Danach verließ Noah sogar den schönen Chiemsee, um sich ab September 2016 im Rahmen der Ausbildung zum Fachinformatiker für Anwendungsentwicklung bei NETWAYS voll und ganz dem Programmieren hinzugeben und viele unterschiedliche Erfahrungen zu sammeln. Wenn er mal nicht am Programmieren und Zocken ist, brettert er mit seinem Snowboard die Pisten runter,...