Combining two independent git repositories

This article presents how to combine two independent and unrelated git repositories.

First, clone the first repository locally and cd into it.

git clone URL_TO_REMOTE_1

Create a branch off the first remote

git checkout -b master-2

In order to combine a completely independent repository into the current one without losing either one’s content, move the existing content of the folder into its own subdirectory (apart from the .git folder). Once done, commit the changes:

mkdir repo-1-content
git mv <existing files/folders> repo-1-content/
git commit -m 'moved repo 1 content into its own subdirectory'

Add the remote of the second repository

git remote add remote-2 URL_TO_REPOSITORY_2

Its content can be pulled into the current branch:

git pull remote-2 master --allow-unrelated-histories

The content of remote-2 will now be part of the git tree of the original remote, under a branch called master-2. Since remote-2’s content still sits at the root of the branch, move it into its own subdirectory as well and commit:

mkdir repo-2-content
git mv <files/folders from remote-2> repo-2-content/
git commit -m 'moved repo 2 content into its own subdirectory'

Master-2 can then be merged into master to finish the combination of the repositories, with each original repository’s content preserved under its own subdirectory.