How to Merge Two Git Repositories

If you need to merge several projects in a single Git Repository without losing history, this snippet is for you. You can use this technique if there the two libraries are similar, and both of the maintainers come together to merge it. Or you need a single repository for the project.

First of all, you need to git clone both projects:

git clone git@server.com:old-project.git
git clone git@server.com:new-project.git

Run the following if you want the old project to be a subdirectory of the new project:

cd old-project
mkdir old-project
git mv !(old-project) old-project
git commit -a -S -m “Moving old project into its own subdirectory”

The next step is the merging part. You should add remote to the old project, and merge everything into the new project. You have to force the project with the allow-unrelated-histories option as Git doesn’t support merges without common history.

cd ../new-project
git remote add old-project ../old-project
git fetch old-project --tags
git checkout -b feature/merge-old-project
git merge -S --allow-unrelated-histories old-project/master
git push origin feature/merge-old-project
git remote rm old-project
Add the --tags option in order to keep tags.

Run git log in order to see the commits of both projects combined into your log.

Merging multiple repositories into single repositories is quite a simple thing to do. In the process of merging repositories merging conflicts may arise. If you’re trying to merge two repositories into one, you can do it this way without using submodules or subtree merges.

The git remote Command

The git remote command is used for creating, viewing, and removing connections to other repositories. Remote connections are considered to be bookmarks in other repositories, which are convenient names used for referencing URLs that are not convenient enough. Using the git remote add command will add a new remote connection to a remote repository. Executing the git remote add command, a new connection record will be created to a remote repository.

Merging Process

The git merge command is used the independent lines of development into a single branch. The git merge command works with the git checkout command to select the current branch. The git checkout -b argument creates a new branch and directly switch to it.

The primary use of git merge is to merge two branches. It is also used to combine multiple commits into one history. It takes two branch tips and finds a common case commit between them. The common base commit creates a new commit that merges the changes in the sequence of each merge commit.


Do you find this helpful?

Related articles