Until recently, my current project had maintained two distinct git repositories, one for each of the major components of the project. For a few reasons, we decided that it would be best to merge them into a single git repository.
Ideally, we wanted to do so in such a way that would preserve the full commit history of each of the two repositories. Fortunately it’s quite easy to accomplish this using a regular git merge
.
Step 1: Preparing the Repositories
You probably don’t want to have the two repositories end up clobbering each other. For our project, we had separate repositories for the backend API and the frontend application. I simply made one commit for each repository that moved all the files into a subdirectory. I.e., all the files in the API repository were moved into the api/
subfolder, and all files in the frontend repository were moved into frontend/
Step 2: Preparing to Merge
Before we can merge, we need to pick one of the repositories and add a remote for the other repository.
I chose to merge the API repository into the frontend repository, so, within the frontend repository, I simply did:
git remote add api-origin
git fetch --all
Doing a git fetch is required to pull in information about the other repository’s commits and branches.
Step 3: Merging
This is the easy part. Simply use git merge
. Here’s how it looked for us:
git merge api-origin/master
You’ll be prompted to make a merge commit. You may also find that some hidden files conflicted, such as your .gitignore
files. These should be easy enough to resolve.
It’s now a good idea to remove the remote for the other repository.
git remote remove api-origin
Wrapping Up
The result of all this is that the entire history for our two repositories has been melded into one big history. When doing a git log, the commits are shown from both repositories, interleaved together. If you look all the way back, you can even see the initial commits for each side by side.
You may find it worthwhile to tell git to do some garbage collection and pruning, to clean up any commit/history info from the other repository that was not brought in.