Photo by Harrison Haines from Pexels

Merging repositories in git

Fortunately, you can do this quite easily by adding one repo to another as a remote. Read on for a step-by-step guide.

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.

Hint: When moving files around, you may have to use the git mv command to preserve a file’s history. Your git front-end of choice might have a more convenient way of doing this, e.g. TortoiseGit gives you this command when you right-click and drag something:

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

Of course, you could do the same thing using your favourite front-end.

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

If you don’t specify this argument, git will fail with a fatal error if you attempt to merge changes from unrelated repositories.

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

You can now push this to the remote for your designated monorepo.

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