🤝

Merge two Git repositories into one

Category
Advanced Git
Published on
December 4, 2022
📖  Table of content

    Sometimes, you wished you have created one single Git repo, instead of two separates. Merging two Git repositories into one can help to combine different projects into one larger project, or to combine the work of two teams into one version-controlled repository. It can also help to keep your work organized by having all of your related projects in one place.

    Fortunately, it is possible to merge two repositories with only 5 steps. We’ll call repo1 the repository that you want to keep, and repo2 the repository that you want to merge into repo1.

    1. Clone the repo that you want to keep and navigate to its local directory:
    2. git clone <link-for-repo1>cd <repo1>
    3. Add repo2 as a remote branch (name it whatever you want) in the first repository, using the following command:
    4. git remote add <repo2-branch-name> <link-for-repo2>
    5. Fetch the latest changes from repo2 using the following command:
    6. git fetch <repo2-branch-name>
    7. Merge the changes from repo2 into repo1, for example in branch master, with:
    8. git checkout mastergit merge <repo2-branch-name> --allow-unrelated-histories

    After running these commands, your destination repository will contain all of the changes from both repositories. You can then push these changes to the remote repository.

    It’s important to note that this process can potentially create conflicts if there are overlapping changes between the two repositories. In this case, you will need to resolve the conflicts manually before you can complete the merge (use git status).