How to Merge Repositories in Git

Abdul Jabbar Feb 02, 2024
How to Merge Repositories in Git

While working on a project with various team members with separate repositories for each team, at a certain time, we come to face a situation where we want to combine these separate repositories into a master repository to deploy all work using a single repository.

Struggling to merge various repositories into one, even preserving its valuable commit history seems difficult, but it’s not actually. In this article, we will elaborate a step by step on how to merge separate repositories into a single master repository.

Steps to Merge Repositories in Git

Suppose we have three repositories: repo A and repo B, and then we have a repo Z, where we want to merge A and B. Let’s assume one more thing we are currently in the directory of repo Z, where we want to merge these two repositories, A & B, into one that is Z.

Let’s suppose one more thing; repo Z is the master branch of the repository.

  1. Add remote URLs

    In this step, we will run the command git remote add with the attribute -f; this will add a remote for repo A, we will name it repo A.

    git remote add -f remote-A <repo-A-URL>
    

    With the option -f, the command git fetch <name> is immediately processed after the remote information has been set up.

    We will follow the same procedure described above for repo B.

    git remote add -f remote-B <repo-B-URL>
    
  2. Combine files and folders

    We will now merge the repo A files into the current branch (repo Z) using the following command.

    git merge remote-A/master --allow-unrelated-histories
    

    Here we will add --allow-unrelated-histories so that Git will allow the merging of unrelated histories.

    Again the same process will be repeated for repo B using the following command.

    git merge remote-B/master --allow-unrelated-histories
    

    If some conflicts arise after running the above command, we will resolve them and then commit the merge successfully.

  3. View commit history

    We will run the following command git log for viewing merged commit history, which would be our final step to view all the merge history of various repositories.

    git log
    
Author: Abdul Jabbar
Abdul Jabbar avatar Abdul Jabbar avatar

Abdul is a software engineer with an architect background and a passion for full-stack web development with eight years of professional experience in analysis, design, development, implementation, performance tuning, and implementation of business applications.

LinkedIn

Related Article - Git Merge