Photo by Harrison Haines from Pexels

Merging repositories in git

Suppose you have two separate git repositories and for some reason, you want to merge them into one. Maybe the source code was originally thought to be independent but was later discovered to be “rightly coupled”. Whatever your reasons, there is probably a commit history in each repository that you want to preserve.

Step 1: Prepare your repositories

Before you migrate your repositories into one, it’s worth going through their directory structures and reorganizing things as needed to avoid clashes. Any file or directory that has the same path between repositories will be treated by git as the same file, resulting in merge conflicts.

Git Move with TortoiseGit

Step 2: Choose your destination repository

Decide upfront which repository will host the final merged code. This can be one of the repositories being merged or a brand new one — it doesn’t matter.

Step 3: Add repositories as remotes

Make sure you have the destination repository cloned on your local machine. Now add a remote for every repository that you want to merge, e.g.

git remote add source1 https://example.com/source1.git

Step 4: Pull unrelated history

Pull from each remote to bring in their respective files and history. You’ll need to specify the allow-unrelated-histories argument, e.g.

git pull --allow-unrelated-histories "source1" master

Step 5: Verify and push

You should now have a single repository with files and change history from various sources. Verify this in your git log.

git history from multiple repositories

Some observations

  • Merge conflicts that arise from file name clashes can be handled the same way you handle any other merge conflict, i.e. resolve and commit.
  • This technique allows you to fetch any number of branches from your various source repositories.

Used for this article

  • git version 2.16.2.windows.1
  • TortoiseGit 2.10.0.2

Software developer walking the edge between legacy systems and modern technology. I also make music: https://soundcloud.com/stephanbester