CoderSam
CoderSam

Reputation: 551

How to Merge two different Git repositories?

I have two Github repositories. One repository is on the remote server and another on the local server. Both of them have different commit histories of different files and folders. Now I wanted to merge both of them so that I can have both of them on the remote server as one single repository. Please help!

I have looked for various solutions suggesting as: reset the head of the local repository and then pull the remote repository on the same directory but it doesn't seem to be working:

git reset --soft head ~CommitSHA (First commit of the local repo)

git pull ~giturlofremoterepo (Pulling remote repo in the same directory)

Upvotes: 10

Views: 15473

Answers (2)

michid
michid

Reputation: 10834

In a nutshell you can checkout one repository, add a remote to the second, rebase the second on top of the first and push the result to your new single remote repository:

Clone the first repository and add a remote to the second

git clone https://first.repo
git remote add second https://second.repo

Fetch the second and check its master branch out to a local branch second

git fetch second
git checkout second/master
git checkout -b second

Rebase the master branch of the second repository on top of the master branch of the first. Resolve any potential conflict along the way.

git rebase master second

Push to a new upstream repository

git push -u ...

This results in the two commit histories being concatenated one after each other.

Upvotes: 14

sudesh regmi
sudesh regmi

Reputation: 546

Create a new git repository and initialize with a new README file.

$ mkdir merged_repo
$ cd merged_repo
$ git init 
$ touch README.md
$ git add .
$ git commit -m "Initialize new repo"

Add the first remote repository

$ git remote add -f first_repo `link_to_first_repo`
$ git merge --allow-unrelated-histories first_repo/master

Create a sub directory and move all first_repo files to it.

$ mkdir first_repo
$ mv * first_repo/
$ git add .
$ git commit -m "Move first_repo files to first_repo directory"

Add the second remote repository

$ git remote add -f second_repo `link_to_second_repo`
$ git merge --allow-unrelated-histories second_repo/master

Fix any merge conflicts and complete the merge as follows

$ git merge --continue

Upvotes: 6

Related Questions