Open In App

How to Merge two Git Repositories?

Last Updated : 28 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Merging two Git repositories can be a complex task, especially if they have distinct histories, branches, and commit structures. This guide explores different approaches and details each step involved in merging two Git repositories.

Merge One Repository as a Subtree of Another

This approach involves adding one repository as a subdirectory within another repository, preserving the history of both. This method is useful when you want to keep the two repositories distinct within the combined project structure.

Syntax:

git remote add <remote-name> <repository-url>
git fetch <remote-name>
git read-tree --prefix=<directory-name>/ -u <remote-name>/<branch>
git commit -m "Merge <remote-name> as a subtree"

Example: In this example, we merge the other-repoz into the main as a subtree.

Step 1: Clone the main repository.

git clone https://github.com/your/main.git
cd main

Step 2: Add the second repository as a remote.

git remote add other-repoz https://github.com/your/other-repo.git
Screenshot-2024-05-20-192516
Merge two Git repositories

Step 3: Fetch the changes from the other repository:

git fetch other-repoz
Screenshot-2024-05-20-192830
Merge two Git repositories

Step 4: Merge the other repository into a subdirectory:

git read-tree --prefix=other-repoz/ -u other-repoz/main
git commit -m "Merge other-repoz as a subtree"
Merge 2 Git Repositories as subdirectory
Merge two Git repositories

Next Article
Article Tags :

Similar Reads