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.
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:
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.
You can now push this to the remote for your designated monorepo.
- 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 220.127.116.11