Sometimes, you make a mistake and you start with a lot of git repositories that actually belong to each other and are dependent of each other. You are stuck with these git repositories and you want to combine them into one git repository. But, you don’t want to lose your git history. I suggest, in order to avoid these problems, to start with one git repository when you do not have good reasons to split an application into more repositories. It is easier to split repositories than to combine them and working with one git repository makes the administration a lot easier. However, if you are stuck with too many repositories and want to get rid of them, the guide below will help you.

Below a guide on how you can combine repositories into one new repository.

  1. Assume two git repositories: ‘repository1’ and ‘repository2’.
  2. Checkout ‘repository1’:
    git clone -b <branch name> <source_url>
  3. Remove the remote:
    git remote rm origin
  4. Create a subdirectory ‘repository1’ where you will move the files from ‘repository1’ into:
    mkdir repository1
  5. Move the files with the following git command (do not move them by means of cut-and-paste via the filesystem) where ‘repository1’ is the destination directory. Repeat this for all files and folders:
    git mv <file> repository1
  6. Commit the changes into the local repository:
    git commit -m "Prepare source repo for merge into repo server"
  7.  Create a combined repository and checkout the combined repository:
    git clone -b <branch name> <source_url>
  8. Add the local repository 1 as a remote to the combine repository:
    git remote add origin_repo1 <file path to repository1>
  9. Now pull the changes from the local repository 1 into the combined repository:
    git pull --allow-unrelated-histories origin_repo1 <branch name>
  10. Push the changes to the combined remote repository:
    git push origin --all
  11. Repeat the steps for repository 2.
  12. If you have several branches you want to combine, repeat the above for each branch.

At the end, you have a combined repository with history.