Daniel Keast

Merging git repos

git, linux

A couple of times I’ve wanted to merge two separate git repos into one. This has happened when they are really parts of the same application with the same release cycle, but have been split in a fit of over architecting.

The first step is simple. Add the second repo as a remote:

git remote add second-repo ~/second-repo.git
git fetch

Next you need to run the merge command. In git 2.9 the behaviour of the command changed to require a '--allow-unrelated-histories' flag to allow a merge between two branches that share no commits. This makes sense, since it’s an unusual thing to do, and you could end up pushing a huge amount of history accidentally otherwise.

You can just merge the two branches as usual with the flag though:

git merge second-repo/master --allow-unrelated-histories

At this point you’re likely to have all sorts of merge conflicts. It could be that you want to merge the second repo into a subdirectory, or maybe you just need some general shuffling around. Once you’ve made things look as you want, run 'git commit' to create the merge commit.

At this point, you can remove the second-repo remote, and push your merge. Because of the way git works the commits in your local repo will even have the same commit ids as they had in their original home.