Merging git repositories

Posted on Tue 02 February 2021 in Programming

For a project, I decided that can be a good idea to merge a couple of repositories to have a single point where to put all the code, issues, wiki and so on.

I later abandoned the idea, since it not came out as good as I was thinking, but in the end I have done it, so why not to share how to do it ?

The main point was that I'd liked to not lose the commit history of the repos I was merging, so I should find some way to merge even these.

Of course a simple copy of the code does not work, since you loose the commit history.
Luckily git offer a way to do it anyway.

The method I used, and later found in a lot of places so nothing new, is to decide which is the main repository where to add the others and then use the merge command.

Assuming that repoA is the main repository with a project caller ProjectA and repoB is the one I want to add with a project called ProjectB, here is the command to use:

git remote add repoBRemote repoBPath
git fetch repoBRemote
git checkout -b ProjectB repoB/master
mkdir ProjectB
git mv [everything in the procject] ProjectB
git commit -m [commit message]
git checkout master
git merge ProjectB
git commit
git push
git remote rm repoBRemote
git branch -d ProjectB

The end result is a repository with this structure

|--- ProjectA
|       |...
|--- ProjectB
|       |...

and the commit history of both of them.