How Do You Merge Two Git Repositories?

Better Stack Team
Updated on June 24, 2024

Merging two Git repositories involves bringing the contents of one repository into another while preserving the commit history of both repositories. Here's a general approach to merge two Git repositories:

Method 1: Using git remote and git merge:

  1. Add the Source Repository as a Remote: In the destination repository, add the source repository as a remote:

     
    git remote add <remote-name> <source-repo-url>
    

    Replace <remote-name> with a name for the remote (e.g., source) and <source-repo-url> with the URL of the source repository.

  2. Fetch the Source Repository: Fetch the branches and commits from the source repository:

     
    git fetch <remote-name>
    
  3. Merge the Source Repository into the Destination Repository: Merge the branches from the source repository into the destination repository:

     
    git merge <remote-name>/<source-branch> --allow-unrelated-histories
    

    Replace <source-branch> with the branch from the source repository that you want to merge into the destination repository.

Method 2: Using git subtree:

  1. Add the Source Repository as a Subtree: In the destination repository, add the source repository as a subtree:

     
    git subtree add --prefix=<prefix> <source-repo-url> <source-branch> --squash
    

    Replace <prefix> with the directory name where you want to place the source repository contents within the destination repository, <source-repo-url> with the URL of the source repository, and <source-branch> with the branch from the source repository.

  2. Update the Subtree: To pull changes from the source repository into the destination repository, use the subtree merge strategy:

     
    git subtree pull --prefix=<prefix> <source-repo-url> <source-branch> --squash
    

    Replace <prefix>, <source-repo-url>, and <source-branch> as before.

Note:

  • Method 1 is suitable when you want to merge the entire contents of the source repository into the destination repository, preserving separate commit histories.
  • Method 2 is useful for maintaining the source repository as a subdirectory within the destination repository.
  • After merging, resolve any conflicts that may arise during the merge process.
  • Ensure that you have appropriate permissions and access rights to both repositories, especially if they are hosted remotely.
Got an article suggestion? Let us know
Explore more
Git
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.