Merging two Git repositories into one preserving the git history

Nyah C.
2 min readSep 26, 2018

--

git merge

Recently my team and I have been working on two different but related git repositories and then came the time when we decided working on different git repositories will lead to duplication of work and may complicate our CI/CD process unnecessarily. So we agreed I do the merge of these two GitHub repositories preserving the file histories of course!

I had never really done this before even though I understood the concept behind git. I just I should share how I did it and this could help me and/or someone else in the future.

The steps are pretty straight forward with some basic git commands.

  1. Create a new git repository and initialize with a new README file.
$ mkdir merged_repo
$ cd merged_repo
$ git init
$ touch README.md
$ git add .
$ git commit -m "Initialize new repo"

2. Add the first remote repository

$ git remote add -f first_repo `link_to_first_repo`
$ git merge --allow-unrelated-histories first_repo/master

Notice I’m using the --allow-unrelated-histories escape hatch to enable the rare event of merging the histories of two git repos that started independently; bypassing the fatal: refusing to merge unrelated histories error. This is because git merge allows the merging of two branches that have a common base by default preventing parallel git histories from existing in the same project.

3. Create a sub directory and move all first_repo files to it.

$ mkdir first_repo
$ mv * first_repo/
$ git add .
$ git commit -m "Move first_repo files to first_repo directory"

4. Add the second remote repository

$ git remote add -f second_repo `link_to_second_repo`
$ git merge --allow-unrelated-histories second_repo/master

Fix any merge conflicts and complete the merge as follows

$ git merge --continue

Now we have successfully merged two git repositories into one. We preserved the commit histories and file histories of all files; and now can continue refactoring or doing other things related to our project.

Clap for yourself !

--

--