DEV Community

Cover image for Merging Git Repos
savannaac
savannaac

Posted on

Merging Git Repos

For my penultimate project, I made two separate git repositories - one for my Rails API backend and the other for my JavaScript frontend. However, after juggling both, not to mention several individual commits later, I realized that maybe having one repo is better than two. But I didn't want to lose my precious commit history either. Luckily, combining several repos into one is almost just as easy as copying and pasting into a new folder.

How to Merge Multiple Repos

The Repos

  • Repo 1
  • Repo 2
  • New Repo, where I want to have Repo 1 & Repo 2

Beforehand: Create/push a new repository

Create a new repo
echo "# new-repo" >> README.md
git init
git add README.md
git commit -m "first commit"
git branch -M main
git remote add origin git@github.com:your-github/new-repo.git
git push -u origin main

or Push an existing repo
git remote add origin git@github.com:your-github/new-repo.git
git branch -M main
git push -u origin main

merge ahead traffic sign

MeRgE Ahead

Let's start in New Repo and add a remote copy of Repo 1.
git remote add -f repo-1 git@github.com:your-github/repo-1.git
Use the actual name of the directory, as opposed to what you named the repo on GitHub, and the SSH URL.

Next, merge all of Repo 1's folders and files with the flag --allow-unrelated-histories, which allows the combining of unrelated branches into one. . . as long as they're no conflicts.
git merge repo-1/main --allow-unrelated-histories

Enter a commit message, in the command-line text editor, explaining why the merge is necessary.

  1. Press "i" to insert
  2. Write merge message
  3. Press "esc" to escape
  4. Press ":wq" to write & quit
  5. Press enter

If conflicts arise, resolve them and repeat the previous command, git merge repo-1/main --allow-unrelated-histories. (I had one with the README.md file, and I resolved it by accepting changes in my text editor.)

Commit the changes and git log to see that the commit history is still there!!

Repeat, Repeat, Repeat

For Repo 2 and, really, any other repo you want to merge, repeat the previous steps:

  • git remote add -f repo-2 git@github.com:your-github/repo-2.git
  • git merge repo-2/main --allow-unrelated-histories

(Resolve conflicts and re-merge)

Again, commit the changes and git log to check everything.

happy kawaii face

Honestly, the thought of merging multiple repos seemed both annoying and daunting. And I spent a good while madly googling and compiling results. However, the previous steps worked and preserved all my commit history without too much suffering.

Top comments (0)